openinference-instrumentation-google-adk 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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright The OpenInference Authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: openinference-instrumentation-google-adk
3
+ Version: 0.1.0
4
+ Summary: OpenInference Google ADK Instrumentation
5
+ Project-URL: Homepage, https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-google-adk
6
+ Author-email: OpenInference Authors <oss@arize.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Requires-Python: <3.14,>=3.9
20
+ Requires-Dist: openinference-instrumentation>=0.1.32
21
+ Requires-Dist: openinference-semantic-conventions>=0.1.17
22
+ Requires-Dist: opentelemetry-api
23
+ Requires-Dist: opentelemetry-instrumentation
24
+ Requires-Dist: opentelemetry-semantic-conventions
25
+ Requires-Dist: typing-extensions
26
+ Requires-Dist: wrapt
27
+ Provides-Extra: instruments
28
+ Requires-Dist: google-adk>=1.2.1; extra == 'instruments'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # OpenInference Google ADK Instrumentation
32
+
33
+ [![pypi](https://badge.fury.io/py/openinference-instrumentation-google-adk.svg)](https://pypi.org/project/openinference-instrumentation-google-adk/)
34
+
35
+ Python auto-instrumentation library for Google ADK.
36
+
37
+ The traces emitted by this instrumentation are fully OpenTelemetry compatible and can be sent to an OpenTelemetry collector for viewing, such as [`arize-phoenix`](https://github.com/Arize-ai/phoenix)
38
+
39
+ ## Installation
40
+
41
+ ```shell
42
+ pip install openinference-instrumentation-google-adk
43
+ ```
44
+
45
+ ## Quickstart
46
+
47
+ In this example we will instrument a small program that uses Gemini and observe the traces via [`arize-phoenix`](https://github.com/Arize-ai/phoenix).
48
+
49
+ Install packages.
50
+
51
+ ```shell
52
+ pip install openinference-instrumentation-google-adk arize-phoenix opentelemetry-sdk opentelemetry-exporter-otlp
53
+ ```
54
+
55
+ Start the phoenix server so that it is ready to collect traces.
56
+ The Phoenix server runs entirely on your machine and does not send data over the internet.
57
+
58
+ ```shell
59
+ phoenix serve
60
+ ```
61
+
62
+ In a python file, set up the `GoogleADKInstrumentor` and configure the tracer to send traces to Phoenix.
63
+
64
+ ```python
65
+ import asyncio
66
+
67
+ from google.adk.agents import Agent
68
+ from google.adk.runners import InMemoryRunner
69
+ from google.genai import types
70
+
71
+ from openinference.instrumentation.google_adk import GoogleADKInstrumentor
72
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
73
+ from opentelemetry.sdk import trace as trace_sdk
74
+ from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
75
+
76
+ endpoint = "http://127.0.0.1:6006/v1/traces"
77
+ tracer_provider = trace_sdk.TracerProvider()
78
+ tracer_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint)))
79
+ # Optionally, you can also print the spans to the console.
80
+ tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
81
+
82
+ GoogleADKInstrumentor().instrument(tracer_provider=tracer_provider)
83
+
84
+ def get_weather(city: str) -> dict:
85
+ """Retrieves the current weather report for a specified city.
86
+
87
+ Args:
88
+ city (str): The name of the city for which to retrieve the weather report.
89
+
90
+ Returns:
91
+ dict: status and result or error msg.
92
+ """
93
+ if city.lower() == "new york":
94
+ return {
95
+ "status": "success",
96
+ "report": (
97
+ "The weather in New York is sunny with a temperature of 25 degrees"
98
+ " Celsius (77 degrees Fahrenheit)."
99
+ ),
100
+ }
101
+ else:
102
+ return {
103
+ "status": "error",
104
+ "error_message": f"Weather information for '{city}' is not available.",
105
+ }
106
+
107
+ agent = Agent(
108
+ name="test_agent",
109
+ model="gemini-2.0-flash-exp",
110
+ description="Agent to answer questions using tools.",
111
+ instruction="You must use the available tools to find an answer.",
112
+ tools=[get_weather]
113
+ )
114
+
115
+ async def main():
116
+ app_name = "test_instrumentation"
117
+ user_id = "test_user"
118
+ session_id = "test_session"
119
+ runner = InMemoryRunner(agent=agent, app_name=app_name)
120
+ session_service = runner.session_service
121
+ await session_service.create_session(
122
+ app_name=app_name,
123
+ user_id=user_id,
124
+ session_id=session_id
125
+ )
126
+ async for event in runner.run_async(
127
+ user_id=user_id,
128
+ session_id=session_id,
129
+ new_message=types.Content(role="user", parts=[
130
+ types.Part(text="What is the weather in New York?")]
131
+ )
132
+ ):
133
+ if event.is_final_response():
134
+ print(event.content.parts[0].text.strip())
135
+
136
+ if __name__ == "__main__":
137
+ asyncio.run(main())
138
+ ```
139
+
140
+ Since we are using Gemini, we must set the `GOOGLE_API_KEY` environment variable to authenticate with the Gemini API.
141
+
142
+ ```shell
143
+ export GOOGLE_API_KEY=your-api-key
144
+ ```
145
+
146
+ Now simply run the python file and observe the traces in Phoenix.
147
+
148
+ ```shell
149
+ python your_file.py
150
+ ```
@@ -0,0 +1,120 @@
1
+ # OpenInference Google ADK Instrumentation
2
+
3
+ [![pypi](https://badge.fury.io/py/openinference-instrumentation-google-adk.svg)](https://pypi.org/project/openinference-instrumentation-google-adk/)
4
+
5
+ Python auto-instrumentation library for Google ADK.
6
+
7
+ The traces emitted by this instrumentation are fully OpenTelemetry compatible and can be sent to an OpenTelemetry collector for viewing, such as [`arize-phoenix`](https://github.com/Arize-ai/phoenix)
8
+
9
+ ## Installation
10
+
11
+ ```shell
12
+ pip install openinference-instrumentation-google-adk
13
+ ```
14
+
15
+ ## Quickstart
16
+
17
+ In this example we will instrument a small program that uses Gemini and observe the traces via [`arize-phoenix`](https://github.com/Arize-ai/phoenix).
18
+
19
+ Install packages.
20
+
21
+ ```shell
22
+ pip install openinference-instrumentation-google-adk arize-phoenix opentelemetry-sdk opentelemetry-exporter-otlp
23
+ ```
24
+
25
+ Start the phoenix server so that it is ready to collect traces.
26
+ The Phoenix server runs entirely on your machine and does not send data over the internet.
27
+
28
+ ```shell
29
+ phoenix serve
30
+ ```
31
+
32
+ In a python file, set up the `GoogleADKInstrumentor` and configure the tracer to send traces to Phoenix.
33
+
34
+ ```python
35
+ import asyncio
36
+
37
+ from google.adk.agents import Agent
38
+ from google.adk.runners import InMemoryRunner
39
+ from google.genai import types
40
+
41
+ from openinference.instrumentation.google_adk import GoogleADKInstrumentor
42
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
43
+ from opentelemetry.sdk import trace as trace_sdk
44
+ from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
45
+
46
+ endpoint = "http://127.0.0.1:6006/v1/traces"
47
+ tracer_provider = trace_sdk.TracerProvider()
48
+ tracer_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint)))
49
+ # Optionally, you can also print the spans to the console.
50
+ tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
51
+
52
+ GoogleADKInstrumentor().instrument(tracer_provider=tracer_provider)
53
+
54
+ def get_weather(city: str) -> dict:
55
+ """Retrieves the current weather report for a specified city.
56
+
57
+ Args:
58
+ city (str): The name of the city for which to retrieve the weather report.
59
+
60
+ Returns:
61
+ dict: status and result or error msg.
62
+ """
63
+ if city.lower() == "new york":
64
+ return {
65
+ "status": "success",
66
+ "report": (
67
+ "The weather in New York is sunny with a temperature of 25 degrees"
68
+ " Celsius (77 degrees Fahrenheit)."
69
+ ),
70
+ }
71
+ else:
72
+ return {
73
+ "status": "error",
74
+ "error_message": f"Weather information for '{city}' is not available.",
75
+ }
76
+
77
+ agent = Agent(
78
+ name="test_agent",
79
+ model="gemini-2.0-flash-exp",
80
+ description="Agent to answer questions using tools.",
81
+ instruction="You must use the available tools to find an answer.",
82
+ tools=[get_weather]
83
+ )
84
+
85
+ async def main():
86
+ app_name = "test_instrumentation"
87
+ user_id = "test_user"
88
+ session_id = "test_session"
89
+ runner = InMemoryRunner(agent=agent, app_name=app_name)
90
+ session_service = runner.session_service
91
+ await session_service.create_session(
92
+ app_name=app_name,
93
+ user_id=user_id,
94
+ session_id=session_id
95
+ )
96
+ async for event in runner.run_async(
97
+ user_id=user_id,
98
+ session_id=session_id,
99
+ new_message=types.Content(role="user", parts=[
100
+ types.Part(text="What is the weather in New York?")]
101
+ )
102
+ ):
103
+ if event.is_final_response():
104
+ print(event.content.parts[0].text.strip())
105
+
106
+ if __name__ == "__main__":
107
+ asyncio.run(main())
108
+ ```
109
+
110
+ Since we are using Gemini, we must set the `GOOGLE_API_KEY` environment variable to authenticate with the Gemini API.
111
+
112
+ ```shell
113
+ export GOOGLE_API_KEY=your-api-key
114
+ ```
115
+
116
+ Now simply run the python file and observe the traces in Phoenix.
117
+
118
+ ```shell
119
+ python your_file.py
120
+ ```
@@ -0,0 +1,96 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "openinference-instrumentation-google-adk"
7
+ dynamic = ["version"]
8
+ description = "OpenInference Google ADK Instrumentation"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.9, <3.14"
12
+ authors = [
13
+ { name = "OpenInference Authors", email = "oss@arize.com" },
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.9",
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
+ ]
27
+ dependencies = [
28
+ "opentelemetry-api",
29
+ "opentelemetry-instrumentation",
30
+ "opentelemetry-semantic-conventions",
31
+ "openinference-instrumentation>=0.1.32",
32
+ "openinference-semantic-conventions>=0.1.17",
33
+ "typing-extensions",
34
+ "wrapt",
35
+ ]
36
+
37
+ [project.optional-dependencies]
38
+ instruments = [
39
+ "google-adk >= 1.2.1",
40
+ ]
41
+
42
+ [project.entry-points.opentelemetry_instrumentor]
43
+ google_adk = "openinference.instrumentation.google_adk:GoogleADKInstrumentor"
44
+
45
+ [project.entry-points.openinference_instrumentor]
46
+ google_adk = "openinference.instrumentation.google_adk:GoogleADKInstrumentor"
47
+
48
+ [project.urls]
49
+ Homepage = "https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-google-adk"
50
+
51
+ [tool.hatch.version]
52
+ path = "src/openinference/instrumentation/google_adk/version.py"
53
+
54
+ [tool.hatch.build.targets.sdist]
55
+ include = [
56
+ "/src",
57
+ ]
58
+
59
+ [tool.hatch.build.targets.wheel]
60
+ packages = ["src/openinference"]
61
+
62
+ [tool.pytest.ini_options]
63
+ asyncio_mode = "auto"
64
+ asyncio_default_fixture_loop_scope = "function"
65
+ testpaths = [
66
+ "tests",
67
+ ]
68
+
69
+ [tool.mypy]
70
+ strict = true
71
+ explicit_package_bases = true
72
+ exclude = [
73
+ "examples",
74
+ "dist",
75
+ "sdist",
76
+ ]
77
+
78
+ [[tool.mypy.overrides]]
79
+ ignore_missing_imports = true
80
+ module = [
81
+ "wrapt",
82
+ ]
83
+
84
+ [tool.ruff]
85
+ line-length = 100
86
+ target-version = "py39"
87
+
88
+ [tool.ruff.lint.per-file-ignores]
89
+ "*.ipynb" = ["E402", "E501"]
90
+ "examples/*" = ["E501"]
91
+
92
+ [tool.ruff.lint]
93
+ select = ["E", "F", "W", "I"]
94
+
95
+ [tool.ruff.lint.isort]
96
+ force-single-line = false
@@ -0,0 +1,187 @@
1
+ import logging
2
+ from typing import Any, Collection, Dict, Iterator, List, Tuple, cast
3
+
4
+ import wrapt
5
+ from opentelemetry import trace as trace_api
6
+ from opentelemetry.instrumentation.instrumentor import ( # type: ignore[attr-defined]
7
+ BaseInstrumentor,
8
+ )
9
+ from opentelemetry.trace import Span, Tracer, get_current_span
10
+ from opentelemetry.util._decorator import _agnosticcontextmanager
11
+ from wrapt import resolve_path, wrap_function_wrapper
12
+
13
+ from openinference.instrumentation import OITracer, TraceConfig
14
+ from openinference.instrumentation.google_adk.version import __version__
15
+
16
+ logger = logging.getLogger(__name__)
17
+ logger.addHandler(logging.NullHandler())
18
+
19
+ _instruments = ("google-adk >= 1.2.1",)
20
+
21
+
22
+ class GoogleADKInstrumentor(BaseInstrumentor): # type: ignore
23
+ def instrumentation_dependencies(self) -> Collection[str]:
24
+ return _instruments
25
+
26
+ def _instrument(self, **kwargs: Any) -> None:
27
+ if not (tracer_provider := kwargs.get("tracer_provider")):
28
+ tracer_provider = trace_api.get_tracer_provider()
29
+ if not (config := kwargs.get("config")):
30
+ config = TraceConfig()
31
+ else:
32
+ assert isinstance(config, TraceConfig)
33
+
34
+ self._tracer = cast(
35
+ Tracer,
36
+ OITracer(
37
+ trace_api.get_tracer(__name__, __version__, tracer_provider),
38
+ config=config,
39
+ ),
40
+ )
41
+
42
+ from google.adk.agents import BaseAgent
43
+ from google.adk.runners import Runner
44
+
45
+ from openinference.instrumentation.google_adk._wrappers import (
46
+ _BaseAgentRunAsync,
47
+ _RunnerRunAsync,
48
+ )
49
+
50
+ # Store original methods for cleanup during uninstrumentation
51
+ self._originals: List[Tuple[Any, Any, Any]] = []
52
+ method_wrappers: Dict[Any, Any] = {
53
+ Runner.run_async: _RunnerRunAsync(self._tracer),
54
+ BaseAgent.run_async: _BaseAgentRunAsync(self._tracer),
55
+ }
56
+
57
+ # Wrap each method with its corresponding tracer
58
+ for method, wrapper in method_wrappers.items():
59
+ module, name = method.__module__, method.__qualname__
60
+ self._originals.append(resolve_path(module, name))
61
+ wrap_function_wrapper(module, name, wrapper)
62
+
63
+ self._patch_trace_call_llm()
64
+ self._patch_trace_tool_call()
65
+ self._disable_existing_tracers()
66
+
67
+ def _uninstrument(self, **kwargs: Any) -> None:
68
+ self._unpatch_trace_call_llm()
69
+ self._unpatch_trace_tool_call()
70
+ self._restore_existing_tracers()
71
+
72
+ # Restore all wrapped methods to their original state
73
+ for parent, attribute, original in getattr(self, "_originals", ()):
74
+ setattr(parent, attribute, original)
75
+
76
+ def _patch_trace_call_llm(self) -> None:
77
+ """Patch the LLM call tracing functionality to use our tracer."""
78
+ from google.adk.flows.llm_flows import base_llm_flow
79
+
80
+ from openinference.instrumentation.google_adk._wrappers import _TraceCallLlm
81
+
82
+ setattr(base_llm_flow, "tracer", self._tracer)
83
+ setattr(
84
+ base_llm_flow,
85
+ "trace_call_llm",
86
+ _TraceCallLlm(self._tracer)(base_llm_flow.trace_call_llm), # type: ignore[attr-defined]
87
+ )
88
+
89
+ def _unpatch_trace_call_llm(self) -> None:
90
+ """Restore the original LLM call tracing functionality."""
91
+ from google.adk.flows.llm_flows import base_llm_flow
92
+
93
+ if callable(
94
+ original := getattr(base_llm_flow.trace_call_llm, "__wrapped__"), # type: ignore[attr-defined]
95
+ ):
96
+ from google.adk.flows.llm_flows import (
97
+ base_llm_flow,
98
+ )
99
+
100
+ setattr(base_llm_flow, "trace_call_llm", original)
101
+
102
+ from google.adk.telemetry import tracer
103
+
104
+ setattr(base_llm_flow, "tracer", tracer)
105
+
106
+ def _patch_trace_tool_call(self) -> None:
107
+ """Patch the tool call tracing functionality to use our tracer."""
108
+ from google.adk.flows.llm_flows import functions
109
+
110
+ from openinference.instrumentation.google_adk._wrappers import _TraceToolCall
111
+
112
+ setattr(functions, "tracer", self._tracer)
113
+ setattr(
114
+ functions,
115
+ "trace_tool_call",
116
+ _TraceToolCall(self._tracer)(functions.trace_tool_call), # type: ignore[attr-defined]
117
+ )
118
+
119
+ def _unpatch_trace_tool_call(self) -> None:
120
+ """Restore the original tool call tracing functionality."""
121
+ from google.adk.flows.llm_flows.base_llm_flow import functions # type: ignore[attr-defined]
122
+
123
+ if callable(
124
+ original := getattr(functions.trace_tool_call, "__wrapped__"), # type: ignore[attr-defined]
125
+ ):
126
+ from google.adk.flows.llm_flows.base_llm_flow import ( # type: ignore[attr-defined]
127
+ functions,
128
+ )
129
+
130
+ setattr(functions, "trace_tool_call", original)
131
+
132
+ from google.adk.telemetry import tracer
133
+
134
+ setattr(functions, "tracer", tracer)
135
+
136
+ def _disable_existing_tracers(self) -> None:
137
+ """Disable existing tracers to prevent double-instrumentation."""
138
+ from google.adk.runners import ( # type: ignore[attr-defined]
139
+ tracer, # pyright: ignore[reportPrivateImportUsage]
140
+ )
141
+
142
+ if isinstance(tracer, Tracer):
143
+ from google.adk import runners
144
+
145
+ setattr(runners, "tracer", _PassthroughTracer(tracer))
146
+
147
+ from google.adk.agents.base_agent import (
148
+ tracer, # pyright: ignore[reportPrivateImportUsage]
149
+ )
150
+
151
+ if isinstance(tracer, Tracer):
152
+ from google.adk.agents import base_agent
153
+
154
+ setattr(base_agent, "tracer", _PassthroughTracer(tracer))
155
+
156
+ def _restore_existing_tracers(self) -> None:
157
+ """Restore original tracers that were disabled during instrumentation."""
158
+ from google.adk.runners import ( # type: ignore[attr-defined]
159
+ tracer, # pyright: ignore[reportPrivateImportUsage]
160
+ )
161
+
162
+ if isinstance(original := getattr(tracer, "__wrapped__"), Tracer):
163
+ from google.adk import runners
164
+
165
+ setattr(runners, "tracer", original)
166
+
167
+ from google.adk.agents.base_agent import (
168
+ tracer, # pyright: ignore[reportPrivateImportUsage]
169
+ )
170
+
171
+ if isinstance(original := getattr(tracer, "__wrapped__"), Tracer):
172
+ from google.adk.agents import base_agent
173
+
174
+ setattr(base_agent, "tracer", original)
175
+
176
+
177
+ class _PassthroughTracer(wrapt.ObjectProxy): # type: ignore[misc]
178
+ """A tracer proxy that passes through span operations without creating new spans.
179
+
180
+ This is used to disable existing tracers during instrumentation to prevent
181
+ double-instrumentation of the same operations.
182
+ """
183
+
184
+ @_agnosticcontextmanager
185
+ def start_as_current_span(self, *args: Any, **kwargs: Any) -> Iterator[Span]:
186
+ """Return the current span without creating a new one."""
187
+ yield get_current_span()
@@ -0,0 +1,522 @@
1
+ import inspect
2
+ import json
3
+ import logging
4
+ from abc import ABC
5
+ from contextlib import ExitStack
6
+ from typing import (
7
+ Any,
8
+ AsyncGenerator,
9
+ Callable,
10
+ Iterable,
11
+ Iterator,
12
+ Mapping,
13
+ OrderedDict,
14
+ TypedDict,
15
+ TypeVar,
16
+ )
17
+
18
+ import wrapt
19
+ from google.adk import Runner
20
+ from google.adk.agents import BaseAgent
21
+ from google.adk.agents.run_config import RunConfig
22
+ from google.adk.events import Event
23
+ from google.adk.models.llm_request import LlmRequest
24
+ from google.adk.models.llm_response import LlmResponse
25
+ from google.adk.telemetry import _build_llm_request_for_trace
26
+ from google.adk.tools import BaseTool
27
+ from google.genai import types
28
+ from google.genai.types import MediaModality
29
+ from opentelemetry import context as context_api
30
+ from opentelemetry import trace as trace_api
31
+ from opentelemetry.context import _SUPPRESS_INSTRUMENTATION_KEY
32
+ from opentelemetry.trace import StatusCode, get_current_span
33
+ from opentelemetry.util.types import AttributeValue
34
+ from typing_extensions import NotRequired, ParamSpec
35
+
36
+ from openinference.instrumentation import (
37
+ get_attributes_from_context,
38
+ safe_json_dumps,
39
+ using_session,
40
+ using_user,
41
+ )
42
+ from openinference.semconv.trace import (
43
+ MessageAttributes,
44
+ MessageContentAttributes,
45
+ OpenInferenceLLMProviderValues,
46
+ OpenInferenceMimeTypeValues,
47
+ OpenInferenceSpanKindValues,
48
+ SpanAttributes,
49
+ ToolAttributes,
50
+ ToolCallAttributes,
51
+ )
52
+
53
+ logger = logging.getLogger(__name__)
54
+ logger.addHandler(logging.NullHandler())
55
+
56
+ P = ParamSpec("P")
57
+ T = TypeVar("T")
58
+
59
+
60
+ class _WithTracer(ABC):
61
+ def __init__(
62
+ self,
63
+ tracer: trace_api.Tracer,
64
+ *args: Any,
65
+ **kwargs: Any,
66
+ ) -> None:
67
+ super().__init__(*args, **kwargs)
68
+ self._tracer = tracer
69
+
70
+
71
+ class _RunnerRunAsyncKwargs(TypedDict):
72
+ user_id: str
73
+ session_id: str
74
+ new_message: types.Content
75
+ run_config: NotRequired[RunConfig]
76
+
77
+
78
+ class _RunnerRunAsync(_WithTracer):
79
+ def __call__(
80
+ self,
81
+ wrapped: Callable[..., AsyncGenerator[Event, None]],
82
+ instance: Runner,
83
+ args: tuple[Any, ...],
84
+ kwargs: _RunnerRunAsyncKwargs,
85
+ ) -> Any:
86
+ generator = wrapped(*args, **kwargs)
87
+ if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
88
+ return generator
89
+
90
+ tracer = self._tracer
91
+ name = f"invocation [{instance.app_name}]"
92
+ attributes = dict(get_attributes_from_context())
93
+ attributes[SpanAttributes.OPENINFERENCE_SPAN_KIND] = OpenInferenceSpanKindValues.CHAIN.value
94
+
95
+ arguments = bind_args_kwargs(wrapped, *args, **kwargs)
96
+ try:
97
+ attributes[SpanAttributes.INPUT_VALUE] = json.dumps(
98
+ arguments,
99
+ default=_default,
100
+ ensure_ascii=False,
101
+ )
102
+ attributes[SpanAttributes.INPUT_MIME_TYPE] = OpenInferenceMimeTypeValues.JSON.value
103
+ except Exception:
104
+ logger.exception(f"Failed to get attribute: {SpanAttributes.INPUT_VALUE}.")
105
+
106
+ if (user_id := kwargs.get("user_id")) is not None:
107
+ attributes[SpanAttributes.USER_ID] = user_id
108
+ if (session_id := kwargs.get("session_id")) is not None:
109
+ attributes[SpanAttributes.SESSION_ID] = session_id
110
+
111
+ class _AsyncGenerator(wrapt.ObjectProxy): # type: ignore[misc]
112
+ __wrapped__: AsyncGenerator[Event, None]
113
+
114
+ async def __aiter__(self) -> Any:
115
+ with ExitStack() as stack:
116
+ span = stack.enter_context(
117
+ tracer.start_as_current_span(
118
+ name=name,
119
+ attributes=attributes,
120
+ )
121
+ )
122
+ if user_id is not None:
123
+ stack.enter_context(using_user(user_id))
124
+ if session_id is not None:
125
+ stack.enter_context(using_session(session_id))
126
+ async for event in self.__wrapped__:
127
+ if event.is_final_response():
128
+ try:
129
+ span.set_attribute(
130
+ SpanAttributes.OUTPUT_VALUE,
131
+ event.model_dump_json(exclude_none=True),
132
+ )
133
+ span.set_attribute(
134
+ SpanAttributes.OUTPUT_MIME_TYPE,
135
+ OpenInferenceMimeTypeValues.JSON.value,
136
+ )
137
+ except Exception:
138
+ logger.exception(
139
+ f"Failed to get attribute: {SpanAttributes.OUTPUT_VALUE}."
140
+ )
141
+ yield event
142
+ span.set_status(StatusCode.OK)
143
+
144
+ return _AsyncGenerator(generator)
145
+
146
+
147
+ class _BaseAgentRunAsync(_WithTracer):
148
+ def __call__(
149
+ self,
150
+ wrapped: Callable[..., AsyncGenerator[Event, None]],
151
+ instance: BaseAgent,
152
+ args: tuple[Any, ...],
153
+ kwargs: Mapping[str, Any],
154
+ ) -> Any:
155
+ generator = wrapped(*args, **kwargs)
156
+ if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
157
+ return generator
158
+
159
+ tracer = self._tracer
160
+ name = f"agent_run [{instance.name}]"
161
+ attributes = dict(get_attributes_from_context())
162
+ attributes[SpanAttributes.OPENINFERENCE_SPAN_KIND] = OpenInferenceSpanKindValues.AGENT.value
163
+
164
+ class _AsyncGenerator(wrapt.ObjectProxy): # type: ignore[misc]
165
+ __wrapped__: AsyncGenerator[Event, None]
166
+
167
+ async def __aiter__(self) -> Any:
168
+ with tracer.start_as_current_span(
169
+ name=name,
170
+ attributes=attributes,
171
+ ) as span:
172
+ async for event in self.__wrapped__:
173
+ if event.is_final_response():
174
+ try:
175
+ span.set_attribute(
176
+ SpanAttributes.OUTPUT_VALUE,
177
+ event.model_dump_json(exclude_none=True),
178
+ )
179
+ span.set_attribute(
180
+ SpanAttributes.OUTPUT_MIME_TYPE,
181
+ OpenInferenceMimeTypeValues.JSON.value,
182
+ )
183
+ except Exception:
184
+ logger.exception(
185
+ f"Failed to get attribute: {SpanAttributes.OUTPUT_VALUE}."
186
+ )
187
+ yield event
188
+ span.set_status(StatusCode.OK)
189
+
190
+ return _AsyncGenerator(generator)
191
+
192
+
193
+ class _TraceCallLlm(_WithTracer):
194
+ @wrapt.decorator # type: ignore[misc]
195
+ def __call__(
196
+ self,
197
+ wrapped: Callable[..., T],
198
+ _: Any,
199
+ args: tuple[Any, ...],
200
+ kwargs: Mapping[str, Any],
201
+ ) -> T:
202
+ ans = wrapped(*args, **kwargs)
203
+ if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
204
+ return ans
205
+ span = get_current_span()
206
+ span.set_status(StatusCode.OK) # Pre-emptively set status to OK
207
+ span.set_attribute(
208
+ SpanAttributes.OPENINFERENCE_SPAN_KIND,
209
+ OpenInferenceSpanKindValues.LLM.value,
210
+ )
211
+ arguments = bind_args_kwargs(wrapped, *args, **kwargs)
212
+ llm_request = next((arg for arg in arguments.values() if isinstance(arg, LlmRequest)), None)
213
+ llm_response = next(
214
+ (arg for arg in arguments.values() if isinstance(arg, LlmResponse)), None
215
+ )
216
+ input_messages_index = 0
217
+ if llm_request:
218
+ span.set_attribute(
219
+ SpanAttributes.LLM_PROVIDER,
220
+ OpenInferenceLLMProviderValues.GOOGLE.value,
221
+ ) # TODO: other providers may also be possible
222
+
223
+ try:
224
+ span.set_attribute(
225
+ SpanAttributes.INPUT_VALUE,
226
+ safe_json_dumps(_build_llm_request_for_trace(llm_request)),
227
+ )
228
+ span.set_attribute(
229
+ SpanAttributes.INPUT_MIME_TYPE,
230
+ OpenInferenceMimeTypeValues.JSON.value,
231
+ )
232
+ except Exception:
233
+ logger.exception(f"Failed to get attribute: {SpanAttributes.INPUT_VALUE}.")
234
+
235
+ if llm_request.tools_dict:
236
+ for i, tool in enumerate(llm_request.tools_dict.values()):
237
+ for k, v in _get_attributes_from_base_tool(
238
+ tool,
239
+ prefix=f"{SpanAttributes.LLM_TOOLS}.{i}.",
240
+ ):
241
+ span.set_attribute(k, v)
242
+
243
+ if llm_request.model:
244
+ span.set_attribute(SpanAttributes.LLM_MODEL_NAME, llm_request.model)
245
+
246
+ if config := llm_request.config:
247
+ for k, v in _get_attributes_from_generate_content_config(config):
248
+ span.set_attribute(k, v)
249
+
250
+ if system_instruction := config.system_instruction:
251
+ span.set_attribute(
252
+ f"{SpanAttributes.LLM_INPUT_MESSAGES}.{input_messages_index}.{MessageAttributes.MESSAGE_ROLE}",
253
+ "system",
254
+ )
255
+ if isinstance(system_instruction, str):
256
+ span.set_attribute(
257
+ f"{SpanAttributes.LLM_INPUT_MESSAGES}.{input_messages_index}.{MessageAttributes.MESSAGE_CONTENT}",
258
+ system_instruction,
259
+ )
260
+ elif isinstance(system_instruction, types.Content):
261
+ if system_instruction.parts:
262
+ for k, v in _get_attributes_from_parts(
263
+ system_instruction.parts,
264
+ prefix=f"{SpanAttributes.LLM_INPUT_MESSAGES}.{input_messages_index}.",
265
+ text_only=True,
266
+ ):
267
+ span.set_attribute(k, v)
268
+ elif isinstance(system_instruction, list):
269
+ # TODO
270
+ pass
271
+ input_messages_index += 1
272
+
273
+ if contents := llm_request.contents:
274
+ for i, content in enumerate(contents, input_messages_index):
275
+ for k, v in _get_attributes_from_content(
276
+ content,
277
+ prefix=f"{SpanAttributes.LLM_INPUT_MESSAGES}.{i}.",
278
+ ):
279
+ span.set_attribute(k, v)
280
+ if llm_response:
281
+ for k, v in _get_attributes_from_llm_response(llm_response):
282
+ span.set_attribute(k, v)
283
+ return ans
284
+
285
+
286
+ class _TraceToolCall(_WithTracer):
287
+ @wrapt.decorator # type: ignore[misc]
288
+ def __call__(
289
+ self,
290
+ wrapped: Callable[..., T],
291
+ _: Any,
292
+ args: tuple[Any, ...],
293
+ kwargs: Mapping[str, Any],
294
+ ) -> T:
295
+ ans = wrapped(*args, **kwargs)
296
+ if context_api.get_value(_SUPPRESS_INSTRUMENTATION_KEY):
297
+ return ans
298
+ span = get_current_span()
299
+ span.set_status(StatusCode.OK) # Pre-emptively set status to OK
300
+ span.set_attribute(
301
+ SpanAttributes.OPENINFERENCE_SPAN_KIND,
302
+ OpenInferenceSpanKindValues.TOOL.value,
303
+ )
304
+ arguments = bind_args_kwargs(wrapped, *args, **kwargs)
305
+ if base_tool := next(
306
+ (arg for arg in arguments.values() if isinstance(arg, BaseTool)), None
307
+ ):
308
+ span.set_attribute(SpanAttributes.TOOL_NAME, base_tool.name)
309
+ span.set_attribute(SpanAttributes.TOOL_DESCRIPTION, base_tool.description)
310
+ if args_dict := next(
311
+ (arg for arg in arguments.values() if isinstance(arg, Mapping)), None
312
+ ):
313
+ try:
314
+ span.set_attribute(
315
+ SpanAttributes.TOOL_PARAMETERS,
316
+ safe_json_dumps(args_dict),
317
+ )
318
+ span.set_attribute(
319
+ SpanAttributes.INPUT_VALUE,
320
+ safe_json_dumps(args_dict),
321
+ )
322
+ span.set_attribute(
323
+ SpanAttributes.INPUT_MIME_TYPE,
324
+ OpenInferenceMimeTypeValues.JSON.value,
325
+ )
326
+ except Exception:
327
+ logger.exception(f"Failed to get attribute: {SpanAttributes.INPUT_VALUE}.")
328
+ if event := next((arg for arg in arguments.values() if isinstance(arg, Event)), None):
329
+ if responses := event.get_function_responses():
330
+ try:
331
+ span.set_attribute(
332
+ SpanAttributes.OUTPUT_VALUE,
333
+ responses[0].model_dump_json(exclude_none=True),
334
+ )
335
+ span.set_attribute(
336
+ SpanAttributes.OUTPUT_MIME_TYPE,
337
+ OpenInferenceMimeTypeValues.JSON.value,
338
+ )
339
+ except Exception:
340
+ logger.exception(f"Failed to get attribute in {wrapped.__name__}.")
341
+ return ans
342
+
343
+
344
+ def stop_on_exception(
345
+ wrapped: Callable[P, Iterator[tuple[str, AttributeValue]]],
346
+ ) -> Callable[P, Iterator[tuple[str, AttributeValue]]]:
347
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Iterator[tuple[str, AttributeValue]]:
348
+ try:
349
+ yield from wrapped(*args, **kwargs)
350
+ except Exception:
351
+ logger.exception(f"Failed to get attribute in {wrapped.__name__}.")
352
+
353
+ return wrapper
354
+
355
+
356
+ @stop_on_exception
357
+ def _get_attributes_from_generate_content_config(
358
+ obj: types.GenerateContentConfig,
359
+ ) -> Iterator[tuple[str, AttributeValue]]:
360
+ yield SpanAttributes.LLM_INVOCATION_PARAMETERS, obj.model_dump_json(exclude_none=True)
361
+
362
+
363
+ @stop_on_exception
364
+ def _get_attributes_from_llm_response(
365
+ obj: LlmResponse,
366
+ ) -> Iterator[tuple[str, AttributeValue]]:
367
+ yield SpanAttributes.OUTPUT_VALUE, obj.model_dump_json(exclude_none=True)
368
+ yield SpanAttributes.OUTPUT_MIME_TYPE, OpenInferenceMimeTypeValues.JSON.value
369
+ if obj.usage_metadata:
370
+ yield from _get_attributes_from_usage_metadata(obj.usage_metadata)
371
+ if obj.content:
372
+ yield from _get_attributes_from_content(
373
+ obj.content, prefix=f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0."
374
+ )
375
+
376
+
377
+ @stop_on_exception
378
+ def _get_attributes_from_usage_metadata(
379
+ obj: types.GenerateContentResponseUsageMetadata,
380
+ ) -> Iterator[tuple[str, AttributeValue]]:
381
+ if obj.candidates_token_count:
382
+ yield SpanAttributes.LLM_TOKEN_COUNT_COMPLETION, obj.candidates_token_count
383
+ if obj.candidates_tokens_details:
384
+ completion_details_audio = 0
385
+ for modality_token_count in obj.candidates_tokens_details:
386
+ if (
387
+ modality_token_count.modality is MediaModality.AUDIO
388
+ and modality_token_count.token_count
389
+ ):
390
+ completion_details_audio += modality_token_count.token_count
391
+ if completion_details_audio:
392
+ yield SpanAttributes.LLM_TOKEN_COUNT_COMPLETION_DETAILS_AUDIO, completion_details_audio
393
+ if obj.prompt_token_count:
394
+ yield SpanAttributes.LLM_TOKEN_COUNT_PROMPT, obj.prompt_token_count
395
+ if obj.total_token_count:
396
+ yield SpanAttributes.LLM_TOKEN_COUNT_TOTAL, obj.total_token_count
397
+
398
+
399
+ @stop_on_exception
400
+ def _get_attributes_from_content(
401
+ obj: types.Content,
402
+ /,
403
+ *,
404
+ prefix: str = "",
405
+ ) -> Iterator[tuple[str, AttributeValue]]:
406
+ role = obj.role or "user"
407
+ yield f"{prefix}{MessageAttributes.MESSAGE_ROLE}", role
408
+ if parts := obj.parts:
409
+ yield from _get_attributes_from_parts(parts, prefix=prefix)
410
+
411
+
412
+ @stop_on_exception
413
+ def _get_attributes_from_parts(
414
+ obj: Iterable[types.Part],
415
+ /,
416
+ *,
417
+ prefix: str = "",
418
+ text_only: bool = False,
419
+ ) -> Iterator[tuple[str, AttributeValue]]:
420
+ for i, part in enumerate(obj):
421
+ if (text := part.text) is not None:
422
+ yield from _get_attributes_from_text_part(
423
+ text,
424
+ prefix=f"{prefix}{MessageAttributes.MESSAGE_CONTENTS}.{i}.",
425
+ )
426
+ elif text_only:
427
+ continue
428
+ elif (function_call := part.function_call) is not None:
429
+ yield from _get_attributes_from_function_call(
430
+ function_call,
431
+ prefix=f"{prefix}{MessageAttributes.MESSAGE_TOOL_CALLS}.{i}.",
432
+ )
433
+ elif (function_response := part.function_response) is not None:
434
+ yield f"{prefix}{MessageAttributes.MESSAGE_ROLE}", "tool"
435
+ if function_response.name:
436
+ yield f"{prefix}{MessageAttributes.MESSAGE_NAME}", function_response.name
437
+ if function_response.response:
438
+ yield (
439
+ f"{prefix}{MessageAttributes.MESSAGE_CONTENT}",
440
+ safe_json_dumps(function_response.response),
441
+ )
442
+
443
+
444
+ @stop_on_exception
445
+ def _get_attributes_from_text_part(
446
+ obj: str,
447
+ /,
448
+ *,
449
+ prefix: str = "",
450
+ ) -> Iterator[tuple[str, AttributeValue]]:
451
+ yield f"{prefix}{MessageContentAttributes.MESSAGE_CONTENT_TEXT}", obj
452
+ yield f"{prefix}{MessageContentAttributes.MESSAGE_CONTENT_TYPE}", "text"
453
+
454
+
455
+ @stop_on_exception
456
+ def _get_attributes_from_function_call(
457
+ obj: types.FunctionCall,
458
+ /,
459
+ *,
460
+ prefix: str = "",
461
+ ) -> Iterator[tuple[str, AttributeValue]]:
462
+ if id_ := obj.id:
463
+ yield f"{prefix}{ToolCallAttributes.TOOL_CALL_ID}", id_
464
+ if name := obj.name:
465
+ yield f"{prefix}{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}", name
466
+ if function_arguments := obj.args:
467
+ yield (
468
+ f"{prefix}{ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON}",
469
+ safe_json_dumps(function_arguments),
470
+ )
471
+
472
+
473
+ @stop_on_exception
474
+ def _get_attributes_from_function_response(
475
+ obj: types.FunctionResponse,
476
+ /,
477
+ *,
478
+ prefix: str = "",
479
+ ) -> Iterator[tuple[str, AttributeValue]]:
480
+ if id_ := obj.id:
481
+ yield f"{prefix}{ToolCallAttributes.TOOL_CALL_ID}", id_
482
+ if name := obj.name:
483
+ yield f"{prefix}{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}", name
484
+ if response := obj.response:
485
+ yield (
486
+ f"{prefix}{ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON}",
487
+ safe_json_dumps(response),
488
+ )
489
+
490
+
491
+ @stop_on_exception
492
+ def _get_attributes_from_base_tool(
493
+ obj: BaseTool,
494
+ /,
495
+ *,
496
+ prefix: str = "",
497
+ ) -> Iterator[tuple[str, AttributeValue]]:
498
+ if declaration := obj._get_declaration():
499
+ tool_json_schema = declaration.model_dump_json(exclude_none=True)
500
+ else:
501
+ tool_json_schema = json.dumps({"name": obj.name, "description": obj.description})
502
+ yield f"{prefix}{ToolAttributes.TOOL_JSON_SCHEMA}", tool_json_schema
503
+
504
+
505
+ def bind_args_kwargs(func: Any, *args: Any, **kwargs: Any) -> OrderedDict[str, Any]:
506
+ sig = inspect.signature(func)
507
+ bound = sig.bind(*args, **kwargs)
508
+ bound.apply_defaults()
509
+ return bound.arguments
510
+
511
+
512
+ def _default(obj: Any) -> str:
513
+ from pydantic import BaseModel
514
+
515
+ if isinstance(obj, BaseModel):
516
+ return json.dumps(
517
+ obj.model_dump(exclude=None),
518
+ ensure_ascii=False,
519
+ default=str,
520
+ )
521
+ else:
522
+ return str(obj)