opentelemetry-instrumentation-openai 0.1.0
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.
- checksums.yaml +7 -0
- data/.yardopts +9 -0
- data/CHANGELOG.md +8 -0
- data/LICENSE +201 -0
- data/README.md +98 -0
- data/lib/opentelemetry/instrumentation/openai/instrumentation.rb +67 -0
- data/lib/opentelemetry/instrumentation/openai/patches/client.rb +264 -0
- data/lib/opentelemetry/instrumentation/openai/patches/operation_name.rb +88 -0
- data/lib/opentelemetry/instrumentation/openai/patches/stream_wrapper.rb +243 -0
- data/lib/opentelemetry/instrumentation/openai/patches/utils.rb +131 -0
- data/lib/opentelemetry/instrumentation/openai/version.rb +13 -0
- data/lib/opentelemetry/instrumentation/openai.rb +19 -0
- data/lib/opentelemetry/instrumentation.rb +19 -0
- data/lib/opentelemetry-instrumentation-openai.rb +7 -0
- metadata +71 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: bd2d758e59ae65650bb0f728a5aeb528b490c0c578fdd38fd5f682d2ce10f85b
|
|
4
|
+
data.tar.gz: b25990affc49f8f35b5b684d786c3ddf14d5d019c0ed4145e76069983bab02a8
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 7a7c1a0d9c85da6c4d3ce71b1b31fdf2db4cefef1fb03174f79a73001b524116e42771e5a0529e7482d3b02ae431f16ffdff3fc9ca922cb775e535c6e28ef2d4
|
|
7
|
+
data.tar.gz: 626a32d4ce28d579ed45502e4d7d785b69115484eee8445c8bb964c831d8162a2f25f6323fecd0f412927f31d9cc5938c71a942326e2b03eb98bac1a5d65c8ea
|
data/.yardopts
ADDED
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Release History: opentelemetry-instrumentation-openai
|
|
2
|
+
|
|
3
|
+
## v0.1.0 / 2026-10-06
|
|
4
|
+
|
|
5
|
+
- ADDED: Add instrumentation for openai gem (#1797)
|
|
6
|
+
- ADDED: Update OpenAI instrumentation for logs and CI (#2552)
|
|
7
|
+
- ADDED: Add meter and logger alongside tracer (#2586)
|
|
8
|
+
- ADDED: Emit log records through the instrumentation-base logger (#2613)
|
data/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright The OpenTelemetry Authors
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
data/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# OpenTelemetry OpenAI Instrumentation
|
|
2
|
+
|
|
3
|
+
The OpenAI instrumentation is a community-maintained instrumentation for the [OpenAI][openai-home] gem.
|
|
4
|
+
|
|
5
|
+
Attributes and events follow the [OpenTelemetry Semantic Conventions for Generative AI][semconv-genai], pinned to core semantic conventions version `1.44.0`.
|
|
6
|
+
|
|
7
|
+
## How do I get started?
|
|
8
|
+
|
|
9
|
+
Install the gem using:
|
|
10
|
+
|
|
11
|
+
```console
|
|
12
|
+
gem install opentelemetry-instrumentation-openai
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Or, if you use [bundler][bundler-home], include `opentelemetry-instrumentation-openai` in your `Gemfile`.
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
To use the instrumentation, call `use` with the name of the instrumentation:
|
|
20
|
+
|
|
21
|
+
```ruby
|
|
22
|
+
OpenTelemetry::SDK.configure do |c|
|
|
23
|
+
c.use 'OpenTelemetry::Instrumentation::OpenAI'
|
|
24
|
+
end
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Alternatively, you can also call `use_all` to install all the available instrumentation.
|
|
28
|
+
|
|
29
|
+
```ruby
|
|
30
|
+
OpenTelemetry::SDK.configure do |c|
|
|
31
|
+
c.use_all
|
|
32
|
+
end
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Configuration options
|
|
36
|
+
|
|
37
|
+
The instrumentation accepts the following configuration options:
|
|
38
|
+
|
|
39
|
+
| Option | Default | Description |
|
|
40
|
+
| --- | --- | --- |
|
|
41
|
+
| `:capture_content` | `false` | Captures the content of prompts and responses (chat messages, inputs, prompts, and tool call arguments) as structured `gen_ai` log records emitted through the OpenTelemetry Logs API. Disabled by default to avoid recording potentially sensitive data. This option is overridden at install time by the `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` environment variable. |
|
|
42
|
+
| `:allowed_operations` | `["chat", "completions", "embeddings"]` | The list of OpenAI operations to instrument. Only requests whose resolved operation name is included here produce spans; all other operations pass through untouched. |
|
|
43
|
+
|
|
44
|
+
Options are passed to `use` in the SDK configuration:
|
|
45
|
+
|
|
46
|
+
```ruby
|
|
47
|
+
OpenTelemetry::SDK.configure do |c|
|
|
48
|
+
c.use 'OpenTelemetry::Instrumentation::OpenAI', {
|
|
49
|
+
capture_content: true,
|
|
50
|
+
allowed_operations: %w[chat completions embeddings]
|
|
51
|
+
}
|
|
52
|
+
end
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Content capture can also be enabled without changing code by setting the
|
|
56
|
+
environment variable:
|
|
57
|
+
|
|
58
|
+
```console
|
|
59
|
+
export OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Emitting log events
|
|
63
|
+
|
|
64
|
+
[GenAI semantic conventions define events to emit with instrumentation][genai-semconv-events]. Events are emitted using the Logs signal. Without a Logs SDK, log records go to a no-op logger. To export them, add the Logs SDK to your Gemfile:
|
|
65
|
+
|
|
66
|
+
```ruby
|
|
67
|
+
gem 'opentelemetry-logs-sdk'
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Examples
|
|
71
|
+
|
|
72
|
+
See [example/trace_demonstration.rb][example-github] for a runnable example that instruments chat completion, streaming, and embeddings requests and prints spans and log records to the console. Set the `OPENAI_API_KEY` environment variable before running it.
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
OPENAI_API_KEY=<openai_api_key> ruby trace_demonstration.rb
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## How can I get involved?
|
|
79
|
+
|
|
80
|
+
The `opentelemetry-instrumentation-openai` gem source is [on github][repo-github], along with related gems including `opentelemetry-api` and `opentelemetry-sdk`.
|
|
81
|
+
|
|
82
|
+
The OpenTelemetry Ruby gems are maintained by the OpenTelemetry Ruby special interest group (SIG). You can get involved by joining us on our [GitHub Discussions][discussions-url], [Slack Channel][slack-channel] or attending our weekly meeting. See the [meeting calendar][community-meetings] for dates and times. For more information on this and other language SIGs, see the OpenTelemetry [community page][ruby-sig].
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
The `opentelemetry-instrumentation-openai` gem is distributed under the Apache 2.0 license. See [LICENSE][license-github] for more information.
|
|
87
|
+
|
|
88
|
+
[openai-home]: https://github.com/openai/openai-ruby
|
|
89
|
+
[bundler-home]: https://bundler.io
|
|
90
|
+
[repo-github]: https://github.com/open-telemetry/opentelemetry-ruby
|
|
91
|
+
[license-github]: https://github.com/open-telemetry/opentelemetry-ruby-contrib/blob/main/LICENSE
|
|
92
|
+
[ruby-sig]: https://github.com/open-telemetry/community#ruby-sig
|
|
93
|
+
[community-meetings]: https://github.com/open-telemetry/community#community-meetings
|
|
94
|
+
[slack-channel]: https://cloud-native.slack.com/archives/C01NWKKMKMY
|
|
95
|
+
[discussions-url]: https://github.com/open-telemetry/opentelemetry-ruby/discussions
|
|
96
|
+
[semconv-genai]: https://github.com/open-telemetry/semantic-conventions-genai
|
|
97
|
+
[example-github]: https://github.com/open-telemetry/opentelemetry-ruby-contrib/blob/main/instrumentation/openai/example/trace_demonstration.rb
|
|
98
|
+
[genai-semconv-events]: https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-events.md
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Copyright The OpenTelemetry Authors
|
|
4
|
+
#
|
|
5
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
|
|
7
|
+
module OpenTelemetry
|
|
8
|
+
module Instrumentation
|
|
9
|
+
module OpenAI
|
|
10
|
+
# The Instrumentation class contains logic to detect and install the openai instrumentation
|
|
11
|
+
class Instrumentation < OpenTelemetry::Instrumentation::Base
|
|
12
|
+
MINIMUM_VERSION = Gem::Version.new('0.35.2')
|
|
13
|
+
ALLOWED_OPERATIONS = %w[chat completions embeddings].freeze
|
|
14
|
+
|
|
15
|
+
install do |_config|
|
|
16
|
+
require_dependencies
|
|
17
|
+
determine_the_content_mode
|
|
18
|
+
patch_client
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
present do
|
|
22
|
+
defined?(::OpenAI)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
compatible do
|
|
26
|
+
gem_version >= MINIMUM_VERSION
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Captures the content of prompts and responses (e.g. chat messages, inputs,
|
|
30
|
+
# prompts, and tool call arguments) as structured `gen_ai` log records.
|
|
31
|
+
# Disabled by default to avoid recording potentially sensitive data. When
|
|
32
|
+
# enabled, message content is emitted through the OpenTelemetry Logs API
|
|
33
|
+
# via the configured logger provider.
|
|
34
|
+
#
|
|
35
|
+
# This option is overridden at install time by the
|
|
36
|
+
# `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` environment variable
|
|
37
|
+
# (see #determine_the_content_mode).
|
|
38
|
+
option :capture_content, default: false, validate: :boolean
|
|
39
|
+
|
|
40
|
+
# The list of OpenAI operations to instrument. Only requests whose resolved
|
|
41
|
+
# operation name is included here produce spans; all other operations pass
|
|
42
|
+
# through untouched. Defaults to ALLOWED_OPERATIONS (chat, completions,
|
|
43
|
+
# embeddings), the operations currently implemented and tested.
|
|
44
|
+
option :allowed_operations, default: ALLOWED_OPERATIONS, validate: :array
|
|
45
|
+
|
|
46
|
+
private
|
|
47
|
+
|
|
48
|
+
def gem_version
|
|
49
|
+
::OpenAI::VERSION
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def determine_the_content_mode
|
|
53
|
+
env_value = ENV['OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT'].to_s
|
|
54
|
+
config[:capture_content] = env_value.downcase == 'true' unless env_value.empty?
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def require_dependencies
|
|
58
|
+
require_relative 'patches/client'
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def patch_client
|
|
62
|
+
::OpenAI::Client.prepend(Patches::Client)
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
end
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Copyright The OpenTelemetry Authors
|
|
4
|
+
#
|
|
5
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
|
|
7
|
+
require_relative 'operation_name'
|
|
8
|
+
require_relative 'stream_wrapper'
|
|
9
|
+
require_relative 'utils'
|
|
10
|
+
|
|
11
|
+
module OpenTelemetry
|
|
12
|
+
module Instrumentation
|
|
13
|
+
module OpenAI
|
|
14
|
+
module Patches
|
|
15
|
+
# OpenAIClient Patch
|
|
16
|
+
# rubocop:disable-next Metrics/ModuleLength
|
|
17
|
+
module Client
|
|
18
|
+
include OperationName
|
|
19
|
+
include Utils
|
|
20
|
+
|
|
21
|
+
# Intercepts outgoing OpenAI requests to create and manage OpenTelemetry spans.
|
|
22
|
+
def request(req)
|
|
23
|
+
operation_name = determine_operation_name(req)
|
|
24
|
+
|
|
25
|
+
# Only instrument implemented/tested OpenAI operations
|
|
26
|
+
return super unless config[:allowed_operations].include? operation_name
|
|
27
|
+
|
|
28
|
+
model = get_property_value(req[:body], 'model')
|
|
29
|
+
span_name = model.to_s.empty? ? operation_name : "#{operation_name} #{model}"
|
|
30
|
+
attributes = extract_request_attributes(req, operation_name, model)
|
|
31
|
+
|
|
32
|
+
# For streaming, start span manually so it stays open during iteration
|
|
33
|
+
# Stream mode return OpenAI::Internal::Stream[OpenAI::Models::Chat::ChatCompletionChunk]
|
|
34
|
+
if req[:stream]
|
|
35
|
+
span = tracer.start_span(span_name, attributes: attributes, kind: :client)
|
|
36
|
+
log_request_content(span, req)
|
|
37
|
+
|
|
38
|
+
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
39
|
+
begin
|
|
40
|
+
response = super
|
|
41
|
+
rescue StandardError => e
|
|
42
|
+
handle_span_exception(span, e)
|
|
43
|
+
raise
|
|
44
|
+
end
|
|
45
|
+
return StreamWrapper.new(response, span, config[:capture_content], start_time)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Non-streaming path
|
|
49
|
+
tracer.in_span(
|
|
50
|
+
span_name,
|
|
51
|
+
attributes: attributes,
|
|
52
|
+
kind: :client
|
|
53
|
+
) do |span|
|
|
54
|
+
# Log request details if content capture is enabled and
|
|
55
|
+
log_request_content(span, req)
|
|
56
|
+
|
|
57
|
+
response = super
|
|
58
|
+
handle_response(span, response, req)
|
|
59
|
+
|
|
60
|
+
response
|
|
61
|
+
rescue StandardError => e
|
|
62
|
+
handle_span_exception(span, e)
|
|
63
|
+
raise
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
private
|
|
68
|
+
|
|
69
|
+
def tracer
|
|
70
|
+
OpenAI::Instrumentation.instance.tracer
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def config
|
|
74
|
+
OpenAI::Instrumentation.instance.config
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# Extract comprehensive request attributes following semantic conventions
|
|
78
|
+
def extract_request_attributes(req, operation_name, model)
|
|
79
|
+
uri = begin
|
|
80
|
+
URI.parse(req[:url])
|
|
81
|
+
rescue StandardError
|
|
82
|
+
nil
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
request_attributes = {
|
|
86
|
+
'gen_ai.operation.name' => operation_name,
|
|
87
|
+
'gen_ai.provider.name' => 'openai',
|
|
88
|
+
'gen_ai.request.model' => model,
|
|
89
|
+
'server.address' => uri&.host || 'api.openai.com',
|
|
90
|
+
'server.port' => uri&.port || 443,
|
|
91
|
+
'gen_ai.output.type' => get_output_type(operation_name),
|
|
92
|
+
'gen_ai.request.stream' => req[:stream] ? true : nil,
|
|
93
|
+
'openai.api.type' => get_api_type(operation_name)
|
|
94
|
+
}.compact
|
|
95
|
+
|
|
96
|
+
# Extract attributes from request body based on operation name
|
|
97
|
+
merge_body_attributes!(request_attributes, req[:body], operation_name)
|
|
98
|
+
|
|
99
|
+
request_attributes
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# Since only chat and embedding is allowed, so we will only expect 'text' as output
|
|
103
|
+
def get_output_type(operation_name)
|
|
104
|
+
case operation_name
|
|
105
|
+
when 'chat'
|
|
106
|
+
'text'
|
|
107
|
+
when 'images.generate', 'images.edit', 'images.variation'
|
|
108
|
+
'image'
|
|
109
|
+
when 'audio.transcription', 'audio.translation', 'audio.speech'
|
|
110
|
+
'speech'
|
|
111
|
+
else
|
|
112
|
+
'json'
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# Maps the operation name to the underlying OpenAI API family
|
|
117
|
+
def get_api_type(operation_name)
|
|
118
|
+
case operation_name
|
|
119
|
+
when 'chat', 'completions'
|
|
120
|
+
'chat_completions'
|
|
121
|
+
when 'responses', 'responses.input_tokens'
|
|
122
|
+
'responses'
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# Merge body attributes based on operation type
|
|
127
|
+
def merge_body_attributes!(attributes, body, operation_name)
|
|
128
|
+
return unless body.is_a?(Hash)
|
|
129
|
+
|
|
130
|
+
case operation_name
|
|
131
|
+
when 'chat', 'completions'
|
|
132
|
+
merge_chat_attributes!(attributes, body)
|
|
133
|
+
when 'embeddings'
|
|
134
|
+
merge_embeddings_attributes!(attributes, body)
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# Merge chat/completion specific attributes
|
|
139
|
+
def merge_chat_attributes!(attributes, body)
|
|
140
|
+
n_count = body[:n]
|
|
141
|
+
stop_sequences = if body[:stop].is_a?(Array)
|
|
142
|
+
body[:stop]
|
|
143
|
+
else
|
|
144
|
+
(body[:stop] ? [body[:stop]] : nil)
|
|
145
|
+
end
|
|
146
|
+
service_tier = body[:service_tier]&.to_s
|
|
147
|
+
|
|
148
|
+
chat_attributes = {
|
|
149
|
+
'gen_ai.request.temperature' => body[:temperature],
|
|
150
|
+
'gen_ai.request.max_tokens' => body[:max_tokens] || body[:max_completion_tokens],
|
|
151
|
+
'gen_ai.request.top_p' => body[:top_p],
|
|
152
|
+
'gen_ai.request.frequency_penalty' => body[:frequency_penalty],
|
|
153
|
+
'gen_ai.request.presence_penalty' => body[:presence_penalty],
|
|
154
|
+
'gen_ai.request.seed' => body[:seed],
|
|
155
|
+
'gen_ai.request.stop_sequences' => stop_sequences,
|
|
156
|
+
'gen_ai.request.choice.count' => n_count && n_count != 1 ? n_count : nil,
|
|
157
|
+
'gen_ai.request.reasoning.level' => body[:reasoning_effort]&.to_s,
|
|
158
|
+
'openai.request.service_tier' => service_tier && service_tier != 'auto' ? service_tier : nil
|
|
159
|
+
}.compact
|
|
160
|
+
|
|
161
|
+
attributes.merge!(chat_attributes)
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# Merge embeddings specific attributes
|
|
165
|
+
def merge_embeddings_attributes!(attributes, body)
|
|
166
|
+
encoding_formats = body[:encoding_format] ? [body[:encoding_format].to_s] : nil
|
|
167
|
+
|
|
168
|
+
embeddings_attributes = {
|
|
169
|
+
'gen_ai.request.encoding_formats' => encoding_formats
|
|
170
|
+
}.compact
|
|
171
|
+
|
|
172
|
+
attributes.merge!(embeddings_attributes)
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# Create event with request content if enabled
|
|
176
|
+
def log_request_content(span, req)
|
|
177
|
+
return unless config[:capture_content]
|
|
178
|
+
|
|
179
|
+
body = req[:body]
|
|
180
|
+
return unless body.is_a?(Hash)
|
|
181
|
+
|
|
182
|
+
return unless body[:messages].is_a?(Array)
|
|
183
|
+
|
|
184
|
+
body[:messages].each do |message|
|
|
185
|
+
event = message_to_log_event(message, capture_content: true)
|
|
186
|
+
log_structured_event(event)
|
|
187
|
+
end
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
# Handle different response types and extract telemetry data
|
|
191
|
+
def handle_response(span, result, req)
|
|
192
|
+
return unless span.recording?
|
|
193
|
+
|
|
194
|
+
# Set basic response attributes (only for non-streaming responses with these methods)
|
|
195
|
+
response_attributes = {
|
|
196
|
+
'gen_ai.response.model' => result.respond_to?(:model) ? result.model : nil,
|
|
197
|
+
'gen_ai.response.id' => result.respond_to?(:id) ? result.id : nil,
|
|
198
|
+
'openai.response.service_tier' => result.respond_to?(:service_tier) ? result.service_tier&.to_s : nil,
|
|
199
|
+
'openai.response.system_fingerprint' => result.respond_to?(:system_fingerprint) ? result.system_fingerprint : nil
|
|
200
|
+
}.compact
|
|
201
|
+
span.add_attributes(response_attributes)
|
|
202
|
+
|
|
203
|
+
# Handle usage/token information
|
|
204
|
+
set_usage_attributes(span, result.usage) if result.respond_to?(:usage) && result.usage
|
|
205
|
+
|
|
206
|
+
# Handle different completion responses
|
|
207
|
+
if result.respond_to?(:choices) && result.choices&.any?
|
|
208
|
+
handle_chat_completion_response(span, result)
|
|
209
|
+
elsif result.respond_to?(:data) && result.data&.any?
|
|
210
|
+
handle_embeddings_response(span, result) if result.data.first.respond_to?(:embedding)
|
|
211
|
+
end
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
# Handle chat completion response
|
|
215
|
+
def handle_chat_completion_response(span, result)
|
|
216
|
+
finish_reasons = result.choices.map { |x| x.finish_reason.to_s }
|
|
217
|
+
span.set_attribute('gen_ai.response.finish_reasons', finish_reasons) if finish_reasons.any?
|
|
218
|
+
|
|
219
|
+
return unless config[:capture_content]
|
|
220
|
+
|
|
221
|
+
result.choices.each do |choice|
|
|
222
|
+
event = choice_to_log_event(choice, capture_content: true)
|
|
223
|
+
log_structured_event(event)
|
|
224
|
+
end
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# Handle embeddings response
|
|
228
|
+
def handle_embeddings_response(span, result)
|
|
229
|
+
embedding_dimensions = result.data.first.respond_to?(:embedding) ? result.data.first.embedding&.size : nil
|
|
230
|
+
|
|
231
|
+
attributes = {
|
|
232
|
+
'gen_ai.embeddings.dimension.count' => embedding_dimensions
|
|
233
|
+
}.compact
|
|
234
|
+
|
|
235
|
+
span.add_attributes(attributes)
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
# Set token usage attributes
|
|
239
|
+
def set_usage_attributes(span, usage)
|
|
240
|
+
prompt_tokens_details = usage.respond_to?(:prompt_tokens_details) ? usage.prompt_tokens_details : nil
|
|
241
|
+
completion_tokens_details = usage.respond_to?(:completion_tokens_details) ? usage.completion_tokens_details : nil
|
|
242
|
+
|
|
243
|
+
usage_attributes = {
|
|
244
|
+
'gen_ai.usage.input_tokens' => usage.respond_to?(:prompt_tokens) ? usage.prompt_tokens : nil,
|
|
245
|
+
'gen_ai.usage.output_tokens' => usage.respond_to?(:completion_tokens) ? usage.completion_tokens : nil,
|
|
246
|
+
'gen_ai.usage.cache_read.input_tokens' => prompt_tokens_details.respond_to?(:cached_tokens) ? prompt_tokens_details.cached_tokens : nil,
|
|
247
|
+
'gen_ai.usage.reasoning.output_tokens' => completion_tokens_details.respond_to?(:reasoning_tokens) ? completion_tokens_details.reasoning_tokens : nil
|
|
248
|
+
}.compact
|
|
249
|
+
|
|
250
|
+
span.add_attributes(usage_attributes)
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
# Handle span exception
|
|
254
|
+
def handle_span_exception(span, error)
|
|
255
|
+
span.set_attribute('error.type', error.class.name)
|
|
256
|
+
span.record_exception(error)
|
|
257
|
+
span.status = OpenTelemetry::Trace::Status.error(error.message)
|
|
258
|
+
span.finish
|
|
259
|
+
end
|
|
260
|
+
end
|
|
261
|
+
end
|
|
262
|
+
end
|
|
263
|
+
end
|
|
264
|
+
end
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Copyright The OpenTelemetry Authors
|
|
4
|
+
#
|
|
5
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
|
|
7
|
+
module OpenTelemetry
|
|
8
|
+
module Instrumentation
|
|
9
|
+
module OpenAI
|
|
10
|
+
module Patches
|
|
11
|
+
# Determine the operation name from the request path
|
|
12
|
+
module OperationName
|
|
13
|
+
# Maps the request path to a canonical OpenAI operation name.
|
|
14
|
+
def determine_operation_name(req)
|
|
15
|
+
path = req[:path].to_s
|
|
16
|
+
|
|
17
|
+
case path
|
|
18
|
+
when %r{^chat/completions}
|
|
19
|
+
'chat'
|
|
20
|
+
when /^embeddings/
|
|
21
|
+
'embeddings'
|
|
22
|
+
when /^completions/
|
|
23
|
+
'completions'
|
|
24
|
+
when %r{^images/generations}
|
|
25
|
+
'images.generate'
|
|
26
|
+
when %r{^images/edits}
|
|
27
|
+
'images.edit'
|
|
28
|
+
when %r{^images/variations}
|
|
29
|
+
'images.variation'
|
|
30
|
+
when %r{^audio/transcriptions}
|
|
31
|
+
'audio.transcription'
|
|
32
|
+
when %r{^audio/translations}
|
|
33
|
+
'audio.translation'
|
|
34
|
+
when %r{^audio/speech}
|
|
35
|
+
'audio.speech'
|
|
36
|
+
when /^models/
|
|
37
|
+
'models'
|
|
38
|
+
when /^files/
|
|
39
|
+
'files'
|
|
40
|
+
when %r{^fine_tuning/jobs}
|
|
41
|
+
'fine_tuning.jobs'
|
|
42
|
+
when %r{^fine_tuning/alpha/graders/run}
|
|
43
|
+
'fine_tuning.graders.run'
|
|
44
|
+
when %r{^fine_tuning/alpha/graders/validate}
|
|
45
|
+
'fine_tuning.graders.validate'
|
|
46
|
+
when /^fine_tuning/
|
|
47
|
+
'fine_tuning'
|
|
48
|
+
when /^moderations/
|
|
49
|
+
'moderations'
|
|
50
|
+
when /^batches/
|
|
51
|
+
'batches'
|
|
52
|
+
when /^uploads/
|
|
53
|
+
'uploads'
|
|
54
|
+
when /^vector_stores/
|
|
55
|
+
'vector_stores'
|
|
56
|
+
when /^assistants/
|
|
57
|
+
'assistants'
|
|
58
|
+
when %r{^threads/runs}
|
|
59
|
+
'threads.runs'
|
|
60
|
+
when /^threads/
|
|
61
|
+
'threads'
|
|
62
|
+
when /^conversations/
|
|
63
|
+
'conversations'
|
|
64
|
+
when %r{^responses/input_tokens}
|
|
65
|
+
'responses.input_tokens'
|
|
66
|
+
when /^responses/
|
|
67
|
+
'responses'
|
|
68
|
+
when /^containers/
|
|
69
|
+
'containers'
|
|
70
|
+
when /^evals/
|
|
71
|
+
'evals'
|
|
72
|
+
when /^videos/
|
|
73
|
+
'videos'
|
|
74
|
+
when %r{^chatkit/sessions}
|
|
75
|
+
'chatkit.sessions'
|
|
76
|
+
when %r{^chatkit/threads}
|
|
77
|
+
'chatkit.threads'
|
|
78
|
+
when %r{^realtime/client_secrets}
|
|
79
|
+
'realtime.client_secrets'
|
|
80
|
+
else
|
|
81
|
+
'openai.request'
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Copyright The OpenTelemetry Authors
|
|
4
|
+
#
|
|
5
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
|
|
7
|
+
require_relative 'utils'
|
|
8
|
+
|
|
9
|
+
module OpenTelemetry
|
|
10
|
+
module Instrumentation
|
|
11
|
+
module OpenAI
|
|
12
|
+
module Patches
|
|
13
|
+
# Stream wrapper for chat completion streaming
|
|
14
|
+
class StreamWrapper
|
|
15
|
+
include Enumerable
|
|
16
|
+
include Utils
|
|
17
|
+
|
|
18
|
+
attr_reader :stream, :span, :capture_content
|
|
19
|
+
|
|
20
|
+
def initialize(stream, span, capture_content, start_time = nil)
|
|
21
|
+
@stream = stream
|
|
22
|
+
@span = span
|
|
23
|
+
@capture_content = capture_content
|
|
24
|
+
@start_time = start_time
|
|
25
|
+
@time_to_first_chunk = nil
|
|
26
|
+
@response_id = nil
|
|
27
|
+
@response_model = nil
|
|
28
|
+
@service_tier = nil
|
|
29
|
+
@finish_reasons = []
|
|
30
|
+
@prompt_tokens = 0
|
|
31
|
+
@completion_tokens = 0
|
|
32
|
+
@cached_tokens = nil
|
|
33
|
+
@reasoning_tokens = nil
|
|
34
|
+
@choice_buffers = []
|
|
35
|
+
@span_started = true
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Iterates over streaming events, processing each chunk and yielding it to the caller.
|
|
39
|
+
def each(&)
|
|
40
|
+
@stream.each do |event|
|
|
41
|
+
process_event(event)
|
|
42
|
+
yield(event) if block_given?
|
|
43
|
+
end
|
|
44
|
+
rescue StandardError => e
|
|
45
|
+
handle_error(e)
|
|
46
|
+
raise
|
|
47
|
+
ensure
|
|
48
|
+
cleanup
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
private
|
|
52
|
+
|
|
53
|
+
# @param chunk [OpenAI::Models::Chat::ChatCompletionChunk]
|
|
54
|
+
def process_event(chunk)
|
|
55
|
+
record_time_to_first_chunk
|
|
56
|
+
response_metadata(chunk)
|
|
57
|
+
build_streaming_response(chunk)
|
|
58
|
+
usage(chunk)
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def record_time_to_first_chunk
|
|
62
|
+
return unless @start_time
|
|
63
|
+
return if @time_to_first_chunk
|
|
64
|
+
|
|
65
|
+
@time_to_first_chunk = Process.clock_gettime(Process::CLOCK_MONOTONIC) - @start_time
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def response_metadata(chunk)
|
|
69
|
+
@response_model ||= chunk.model if chunk.respond_to?(:model)
|
|
70
|
+
@response_id ||= chunk.id if chunk.respond_to?(:id)
|
|
71
|
+
@service_tier ||= chunk.service_tier if chunk.respond_to?(:service_tier)
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def build_streaming_response(chunk)
|
|
75
|
+
return unless chunk.respond_to?(:choices) && chunk.choices
|
|
76
|
+
|
|
77
|
+
chunk.choices.each do |choice|
|
|
78
|
+
next unless choice.respond_to?(:delta) && choice.delta
|
|
79
|
+
|
|
80
|
+
# Ensure we have enough choice buffers
|
|
81
|
+
index = choice.respond_to?(:index) ? choice.index : 0
|
|
82
|
+
@choice_buffers << ChoiceBuffer.new(@choice_buffers.size) while @choice_buffers.size <= index
|
|
83
|
+
|
|
84
|
+
buffer = @choice_buffers[index]
|
|
85
|
+
buffer.finish_reason = choice.finish_reason if choice.respond_to?(:finish_reason) && choice.finish_reason
|
|
86
|
+
|
|
87
|
+
delta = choice.delta
|
|
88
|
+
buffer.append_content(delta.content) if delta.respond_to?(:content) && delta.content
|
|
89
|
+
buffer.append_tool_calls(delta.tool_calls) if delta.respond_to?(:tool_calls) && delta.tool_calls
|
|
90
|
+
end
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def usage(chunk)
|
|
94
|
+
return unless chunk.respond_to?(:usage) && chunk.usage
|
|
95
|
+
|
|
96
|
+
usage = chunk.usage
|
|
97
|
+
@completion_tokens = usage.completion_tokens if usage.respond_to?(:completion_tokens)
|
|
98
|
+
@prompt_tokens = usage.prompt_tokens if usage.respond_to?(:prompt_tokens)
|
|
99
|
+
|
|
100
|
+
@cached_tokens = usage.prompt_tokens_details.cached_tokens if usage.respond_to?(:prompt_tokens_details) && usage.prompt_tokens_details.respond_to?(:cached_tokens)
|
|
101
|
+
|
|
102
|
+
return unless usage.respond_to?(:completion_tokens_details) && usage.completion_tokens_details.respond_to?(:reasoning_tokens)
|
|
103
|
+
|
|
104
|
+
@reasoning_tokens = usage.completion_tokens_details.reasoning_tokens
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
def cleanup
|
|
108
|
+
return unless @span_started
|
|
109
|
+
|
|
110
|
+
# Set final attributes only if span is still recording
|
|
111
|
+
if @span.recording?
|
|
112
|
+
finish_reasons = @choice_buffers.map { |x| x.finish_reason.to_s }
|
|
113
|
+
attributes = {
|
|
114
|
+
'gen_ai.response.model' => @response_model,
|
|
115
|
+
'gen_ai.response.id' => @response_id,
|
|
116
|
+
'gen_ai.usage.input_tokens' => @prompt_tokens.positive? ? @prompt_tokens : nil,
|
|
117
|
+
'gen_ai.usage.output_tokens' => @completion_tokens.positive? ? @completion_tokens : nil,
|
|
118
|
+
'gen_ai.usage.cache_read.input_tokens' => @cached_tokens,
|
|
119
|
+
'gen_ai.usage.reasoning.output_tokens' => @reasoning_tokens,
|
|
120
|
+
'gen_ai.response.finish_reasons' => finish_reasons.any? ? finish_reasons : nil,
|
|
121
|
+
'gen_ai.response.time_to_first_chunk' => @time_to_first_chunk,
|
|
122
|
+
'openai.response.service_tier' => @service_tier.to_s
|
|
123
|
+
}.compact
|
|
124
|
+
@span.add_attributes(attributes)
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# Emit structured log events for each choice (not span events)
|
|
128
|
+
if @capture_content
|
|
129
|
+
@choice_buffers.each do |buffer|
|
|
130
|
+
event = buffer.to_log_event
|
|
131
|
+
log_structured_event(event)
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
ensure
|
|
135
|
+
@span.finish
|
|
136
|
+
@span_started = false
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def handle_error(error)
|
|
140
|
+
@span.set_attribute('error.type', error.class.name)
|
|
141
|
+
@span.record_exception(error)
|
|
142
|
+
@span.status = OpenTelemetry::Trace::Status.error(error.message)
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# Buffer for accumulating streaming choice data
|
|
146
|
+
class ChoiceBuffer
|
|
147
|
+
attr_accessor :finish_reason
|
|
148
|
+
attr_reader :index, :text_content, :tool_call_buffers
|
|
149
|
+
|
|
150
|
+
def initialize(index)
|
|
151
|
+
@index = index
|
|
152
|
+
@text_content = []
|
|
153
|
+
@tool_call_buffers = []
|
|
154
|
+
@finish_reason = nil
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# Appends a content chunk to the text buffer.
|
|
158
|
+
def append_content(content)
|
|
159
|
+
@text_content << content if content
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
# Appends streaming tool call deltas to their respective buffers.
|
|
163
|
+
def append_tool_calls(tool_calls)
|
|
164
|
+
tool_calls.each do |tool_call|
|
|
165
|
+
# Find or create tool call buffer
|
|
166
|
+
buffer = @tool_call_buffers.find { |b| b.index == tool_call.index } if tool_call.respond_to?(:index)
|
|
167
|
+
|
|
168
|
+
if buffer.nil?
|
|
169
|
+
tc_index = tool_call.respond_to?(:index) ? tool_call.index : @tool_call_buffers.size
|
|
170
|
+
buffer = ToolCallBuffer.new(tc_index)
|
|
171
|
+
@tool_call_buffers << buffer
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
buffer.append(tool_call)
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
# Converts the accumulated choice buffer into a structured log event hash.
|
|
179
|
+
def to_log_event
|
|
180
|
+
body = {
|
|
181
|
+
index: @index,
|
|
182
|
+
finish_reason: @finish_reason&.to_s || 'error',
|
|
183
|
+
message: {
|
|
184
|
+
role: 'assistant'
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
body[:message][:content] = @text_content.join if @text_content.any?
|
|
189
|
+
|
|
190
|
+
if @tool_call_buffers.any?
|
|
191
|
+
tool_calls = @tool_call_buffers.map(&:to_hash)
|
|
192
|
+
body[:message][:tool_calls] = tool_calls
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
{
|
|
196
|
+
event_name: 'gen_ai.choice',
|
|
197
|
+
attributes: {
|
|
198
|
+
'gen_ai.provider.name' => 'openai'
|
|
199
|
+
},
|
|
200
|
+
body: body
|
|
201
|
+
}
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
# Buffer for accumulating tool call data
|
|
206
|
+
class ToolCallBuffer
|
|
207
|
+
attr_reader :index
|
|
208
|
+
|
|
209
|
+
def initialize(index)
|
|
210
|
+
@index = index
|
|
211
|
+
@tool_call_id = nil
|
|
212
|
+
@function_name = nil
|
|
213
|
+
@arguments = []
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
# Accumulates tool call delta data into the buffer.
|
|
217
|
+
def append(tool_call)
|
|
218
|
+
@tool_call_id ||= tool_call.id if tool_call.respond_to?(:id)
|
|
219
|
+
|
|
220
|
+
return unless tool_call.respond_to?(:function) && tool_call.function
|
|
221
|
+
|
|
222
|
+
function = tool_call.function
|
|
223
|
+
@function_name ||= function.name if function.respond_to?(:name)
|
|
224
|
+
@arguments << function.arguments if function.respond_to?(:arguments) && function.arguments
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# Serializes the accumulated tool call buffer to a hash.
|
|
228
|
+
def to_hash
|
|
229
|
+
{
|
|
230
|
+
id: @tool_call_id,
|
|
231
|
+
type: 'function',
|
|
232
|
+
function: {
|
|
233
|
+
name: @function_name,
|
|
234
|
+
arguments: @arguments.join
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
end
|
|
238
|
+
end
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
end
|
|
242
|
+
end
|
|
243
|
+
end
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Copyright The OpenTelemetry Authors
|
|
4
|
+
#
|
|
5
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
|
|
7
|
+
module OpenTelemetry
|
|
8
|
+
module Instrumentation
|
|
9
|
+
module OpenAI
|
|
10
|
+
module Patches
|
|
11
|
+
# Utils
|
|
12
|
+
module Utils
|
|
13
|
+
# Retrieves a property value from a Hash or object by name.
|
|
14
|
+
def get_property_value(obj, property_name)
|
|
15
|
+
if obj.is_a?(Hash)
|
|
16
|
+
obj[property_name] || obj[property_name.to_sym]
|
|
17
|
+
else
|
|
18
|
+
obj.respond_to?(property_name) ? obj.public_send(property_name) : nil
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# Extracts and normalizes tool call data from a message or choice object.
|
|
23
|
+
def extract_tool_calls(item, capture_content)
|
|
24
|
+
tool_calls = get_property_value(item, :tool_calls)
|
|
25
|
+
return nil unless tool_calls
|
|
26
|
+
|
|
27
|
+
calls = []
|
|
28
|
+
tool_calls.each do |tool_call|
|
|
29
|
+
tool_call_dict = {}
|
|
30
|
+
|
|
31
|
+
call_id = get_property_value(tool_call, :id)
|
|
32
|
+
tool_call_dict[:id] = call_id if call_id
|
|
33
|
+
|
|
34
|
+
tool_type = get_property_value(tool_call, :type)
|
|
35
|
+
tool_call_dict[:type] = tool_type.to_s if tool_type
|
|
36
|
+
|
|
37
|
+
func = get_property_value(tool_call, :function)
|
|
38
|
+
if func
|
|
39
|
+
tool_call_dict[:function] = {}
|
|
40
|
+
|
|
41
|
+
name = get_property_value(func, :name)
|
|
42
|
+
tool_call_dict[:function][:name] = name if name
|
|
43
|
+
|
|
44
|
+
arguments = get_property_value(func, :arguments)
|
|
45
|
+
if capture_content && arguments
|
|
46
|
+
arguments = arguments.to_s.delete("\n") if arguments.is_a?(String)
|
|
47
|
+
tool_call_dict[:function][:arguments] = arguments
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
calls << tool_call_dict
|
|
52
|
+
end
|
|
53
|
+
calls
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Converts a request message into a structured gen_ai log event hash.
|
|
57
|
+
def message_to_log_event(message, capture_content: true)
|
|
58
|
+
role = get_property_value(message, :role)&.to_s
|
|
59
|
+
content = get_property_value(message, :content)
|
|
60
|
+
|
|
61
|
+
body = {}
|
|
62
|
+
body[:content] = content.to_s if capture_content && content
|
|
63
|
+
|
|
64
|
+
if role == 'assistant'
|
|
65
|
+
tool_calls = extract_tool_calls(message, capture_content)
|
|
66
|
+
body = { tool_calls: tool_calls } if tool_calls
|
|
67
|
+
elsif role == 'tool'
|
|
68
|
+
tool_call_id = get_property_value(message, :tool_call_id)
|
|
69
|
+
body[:id] = tool_call_id if tool_call_id
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
{
|
|
73
|
+
event_name: "gen_ai.#{role}.message",
|
|
74
|
+
attributes: {
|
|
75
|
+
'gen_ai.provider.name' => 'openai'
|
|
76
|
+
},
|
|
77
|
+
body: body.empty? ? nil : body
|
|
78
|
+
}
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Converts a response choice into a structured gen_ai log event hash.
|
|
82
|
+
def choice_to_log_event(choice, capture_content: true)
|
|
83
|
+
index = get_property_value(choice, :index) || 0
|
|
84
|
+
finish_reason = get_property_value(choice, :finish_reason)&.to_s || 'error'
|
|
85
|
+
|
|
86
|
+
body = {
|
|
87
|
+
index: index,
|
|
88
|
+
finish_reason: finish_reason
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
message_obj = get_property_value(choice, :message)
|
|
92
|
+
if message_obj
|
|
93
|
+
message = {}
|
|
94
|
+
role = get_property_value(message_obj, :role)
|
|
95
|
+
message[:role] = role.to_s if role
|
|
96
|
+
|
|
97
|
+
tool_calls = extract_tool_calls(message_obj, capture_content)
|
|
98
|
+
message[:tool_calls] = tool_calls if tool_calls
|
|
99
|
+
|
|
100
|
+
content = get_property_value(message_obj, :content)
|
|
101
|
+
message[:content] = content.to_s if capture_content && content
|
|
102
|
+
|
|
103
|
+
body[:message] = message
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
{
|
|
107
|
+
event_name: 'gen_ai.choice',
|
|
108
|
+
attributes: {
|
|
109
|
+
'gen_ai.provider.name' => 'openai'
|
|
110
|
+
},
|
|
111
|
+
body: body
|
|
112
|
+
}
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# Emits a structured log record through the OpenTelemetry Logs API.
|
|
116
|
+
def log_structured_event(event)
|
|
117
|
+
Instrumentation.instance.logger.on_emit(
|
|
118
|
+
timestamp: Time.now,
|
|
119
|
+
severity_text: 'INFO',
|
|
120
|
+
severity_number: OpenTelemetry::Logs::SeverityNumber::SEVERITY_NUMBER_INFO,
|
|
121
|
+
event_name: event[:event_name],
|
|
122
|
+
body: event[:body],
|
|
123
|
+
attributes: event[:attributes],
|
|
124
|
+
context: OpenTelemetry::Context.current
|
|
125
|
+
)
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
end
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Copyright The OpenTelemetry Authors
|
|
4
|
+
#
|
|
5
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
|
|
7
|
+
require 'opentelemetry'
|
|
8
|
+
require 'opentelemetry-instrumentation-base'
|
|
9
|
+
|
|
10
|
+
module OpenTelemetry
|
|
11
|
+
module Instrumentation
|
|
12
|
+
# Contains the OpenTelemetry instrumentation for the openai gem
|
|
13
|
+
module OpenAI
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
require_relative 'openai/instrumentation'
|
|
19
|
+
require_relative 'openai/version'
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Copyright The OpenTelemetry Authors
|
|
4
|
+
#
|
|
5
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
6
|
+
|
|
7
|
+
# OpenTelemetry is an open source observability framework, providing a
|
|
8
|
+
# general-purpose API, SDK, and related tools required for the instrumentation
|
|
9
|
+
# of cloud-native software, frameworks, and libraries.
|
|
10
|
+
#
|
|
11
|
+
# The OpenTelemetry module provides global accessors for telemetry objects.
|
|
12
|
+
# See the documentation for the `opentelemetry-api` gem for details.
|
|
13
|
+
module OpenTelemetry
|
|
14
|
+
# Instrumentation should be able to handle the case when the library is not installed on a user's system.
|
|
15
|
+
module Instrumentation
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
require_relative 'instrumentation/openai'
|
metadata
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: opentelemetry-instrumentation-openai
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- OpenTelemetry Authors
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: opentelemetry-instrumentation-base
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - "~>"
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: '0.27'
|
|
19
|
+
type: :runtime
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - "~>"
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: '0.27'
|
|
26
|
+
description: OpenAI instrumentation for the OpenTelemetry framework
|
|
27
|
+
email:
|
|
28
|
+
- cncf-opentelemetry-contributors@lists.cncf.io
|
|
29
|
+
executables: []
|
|
30
|
+
extensions: []
|
|
31
|
+
extra_rdoc_files: []
|
|
32
|
+
files:
|
|
33
|
+
- ".yardopts"
|
|
34
|
+
- CHANGELOG.md
|
|
35
|
+
- LICENSE
|
|
36
|
+
- README.md
|
|
37
|
+
- lib/opentelemetry-instrumentation-openai.rb
|
|
38
|
+
- lib/opentelemetry/instrumentation.rb
|
|
39
|
+
- lib/opentelemetry/instrumentation/openai.rb
|
|
40
|
+
- lib/opentelemetry/instrumentation/openai/instrumentation.rb
|
|
41
|
+
- lib/opentelemetry/instrumentation/openai/patches/client.rb
|
|
42
|
+
- lib/opentelemetry/instrumentation/openai/patches/operation_name.rb
|
|
43
|
+
- lib/opentelemetry/instrumentation/openai/patches/stream_wrapper.rb
|
|
44
|
+
- lib/opentelemetry/instrumentation/openai/patches/utils.rb
|
|
45
|
+
- lib/opentelemetry/instrumentation/openai/version.rb
|
|
46
|
+
homepage: https://github.com/open-telemetry/opentelemetry-ruby-contrib
|
|
47
|
+
licenses:
|
|
48
|
+
- Apache-2.0
|
|
49
|
+
metadata:
|
|
50
|
+
changelog_uri: https://rubydoc.info/gems/opentelemetry-instrumentation-openai/0.1.0/file/CHANGELOG.md
|
|
51
|
+
source_code_uri: https://github.com/open-telemetry/opentelemetry-ruby-contrib/tree/main/instrumentation/openai
|
|
52
|
+
bug_tracker_uri: https://github.com/open-telemetry/opentelemetry-ruby-contrib/issues
|
|
53
|
+
documentation_uri: https://rubydoc.info/gems/opentelemetry-instrumentation-openai/0.1.0
|
|
54
|
+
rdoc_options: []
|
|
55
|
+
require_paths:
|
|
56
|
+
- lib
|
|
57
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
58
|
+
requirements:
|
|
59
|
+
- - ">="
|
|
60
|
+
- !ruby/object:Gem::Version
|
|
61
|
+
version: '3.3'
|
|
62
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
63
|
+
requirements:
|
|
64
|
+
- - ">="
|
|
65
|
+
- !ruby/object:Gem::Version
|
|
66
|
+
version: '0'
|
|
67
|
+
requirements: []
|
|
68
|
+
rubygems_version: 4.0.16
|
|
69
|
+
specification_version: 4
|
|
70
|
+
summary: OpenAI instrumentation for the OpenTelemetry framework
|
|
71
|
+
test_files: []
|