Skip to content

Commit cc1f23e

Browse files
Nagkumar ArkalgudNagkumar Arkalgud
authored andcommitted
Sync openai-agents instrumentation directory from ankit/main
1 parent 5c51e64 commit cc1f23e

File tree

18 files changed

+1522
-1226
lines changed

18 files changed

+1522
-1226
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Changelog
2+
3+
## Unreleased
4+
5+
### Added
6+
7+
- Initial implementation of OpenAI Agents instrumentation
8+
- Support for OpenAI API client tracing in agent frameworks
9+
- Capture of request/response content and metrics
10+
- Configuration options for content capture and metrics collection
11+
12+
### Changed
13+
14+
### Deprecated
15+
16+
### Removed
17+
18+
### Fixed
19+
20+
### Security
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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 granting the License.
13+
14+
"Legal Entity" shall mean the union of the acting entity and all
15+
other entities that control, are controlled by, or are under common
16+
control with that entity. For the purposes of this definition,
17+
"control" means (i) the power, direct or indirect, to cause the
18+
direction or management of such entity, whether by contract or
19+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
20+
outstanding shares, or (iii) beneficial ownership of such entity.
21+
22+
"You" (or "Your") shall mean an individual or Legal Entity
23+
exercising permissions granted by this License.
24+
25+
"Source" form shall mean the preferred form for making modifications,
26+
including but not limited to software source code, documentation
27+
source, and configuration files.
28+
29+
"Object" form shall mean any form resulting from mechanical
30+
transformation or translation of a Source form, including but
31+
not limited to compiled object code, generated documentation,
32+
and conversions to other media types.
33+
34+
"Work" shall mean the work of authorship, whether in Source or
35+
Object form, made available under the License, as indicated by a
36+
copyright notice that is included in or attached to the work
37+
(which shall not include communication that is clearly marked or
38+
otherwise designated in writing by the copyright owner as "Not a Work").
39+
40+
"Derivative Works" shall mean any work, whether in Source or Object
41+
form, that is based upon (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
57+
systems, and issue tracking systems that are managed by, or on behalf
58+
of, the Licensor for the purpose of discussing and improving the Work,
59+
but excluding communication that is clearly 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 use, reproduce, modify, distribute, and prepare
70+
Derivative Works of, publicly display, publicly perform, sublicense,
71+
and distribute the Work and such Derivative Works in Source or Object
72+
form.
73+
74+
3. Grant of Patent License. Subject to the terms and conditions of
75+
this License, each Contributor hereby grants to You a perpetual,
76+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77+
(except as stated in this section) patent license to make, have made,
78+
use, offer to sell, sell, import, and otherwise transfer the Work,
79+
where such license applies only to those patent claims licensable
80+
by such Contributor that are necessarily infringed by their
81+
Contribution(s) alone or by combination of their Contribution(s)
82+
with the Work to which such Contribution(s) was submitted. If You
83+
institute patent litigation against any entity (including a
84+
cross-claim or counterclaim in a lawsuit) alleging that the Work
85+
or a Contribution incorporated within the Work constitutes direct
86+
or contributory patent infringement, then any patent licenses
87+
granted to You under this License for that Work shall terminate
88+
as of the date such litigation is filed.
89+
90+
4. Redistribution. You may reproduce and distribute copies of the
91+
Work or Derivative Works thereof in any medium, with or without
92+
modifications, and in Source or Object form, provided that You
93+
meet the following conditions:
94+
95+
(a) You must give any other recipients of the Work or
96+
Derivative Works a copy of this License; and
97+
98+
(b) You must cause any modified files to carry prominent notices
99+
stating that You changed the files; and
100+
101+
(c) You must retain, in the Source form of any Derivative Works
102+
that You distribute, all copyright, trademark, patent,
103+
attribution and other notices from the Source form of the Work,
104+
excluding those notices that do not pertain to any part of
105+
the Derivative Works; and
106+
107+
(d) If the Work includes a "NOTICE" text file as part of its
108+
distribution, then any Derivative Works that You distribute must
109+
include a readable copy of the attribution notices contained
110+
within such NOTICE file, excluding those notices that do not
111+
pertain to any part of the Derivative Works, in at least one
112+
of the following places: within a NOTICE text file distributed
113+
as part of the Derivative Works; within the Source form or
114+
documentation, if provided along with the Derivative Works; or,
115+
within a display generated by the Derivative Works, if and
116+
wherever such third-party notices normally appear. The contents
117+
of the NOTICE file are for informational purposes only and
118+
do not modify the License. You may add Your own attribution
119+
notices within Derivative Works that You distribute, alongside
120+
or as an addendum to the NOTICE text from the Work, provided
121+
that such additional attribution notices cannot be construed
122+
as modifying the License.
123+
124+
You may add Your own copyright notice to Your modifications and
125+
may provide additional or different license terms and conditions
126+
for use, reproduction, or distribution of Your modifications, or
127+
for any such Derivative Works as a whole, provided Your use,
128+
reproduction, and distribution of the Work otherwise complies with
129+
the conditions stated in this License.
130+
131+
5. Submission of Contributions. Unless You explicitly state otherwise,
132+
any Contribution intentionally submitted for inclusion in the Work
133+
by You to the Licensor shall be under the terms and conditions of
134+
this License, without any additional terms or conditions.
135+
Notwithstanding the above, nothing herein shall supersede or modify
136+
the terms of any separate license agreement you may have executed
137+
with Licensor regarding such Contributions.
138+
139+
6. Trademarks. This License does not grant permission to use the trade
140+
names, trademarks, service marks, or product names of the Licensor,
141+
except as required for reasonable and customary use in describing the
142+
origin of the Work and reproducing the content of the NOTICE file.
143+
144+
7. Disclaimer of Warranty. Unless required by applicable law or
145+
agreed to in writing, Licensor provides the Work (and each
146+
Contributor provides its Contributions) on an "AS IS" BASIS,
147+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148+
implied, including, without limitation, any warranties or conditions
149+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150+
PARTICULAR PURPOSE. You are solely responsible for determining the
151+
appropriateness of using or redistributing the Work and assume any
152+
risks associated with Your exercise of permissions under this License.
153+
154+
8. Limitation of Liability. In no event and under no legal theory,
155+
whether in tort (including negligence), contract, or otherwise,
156+
unless required by applicable law (such as deliberate and grossly
157+
negligent acts) or agreed to in writing, shall any Contributor be
158+
liable to You for damages, including any direct, indirect, special,
159+
incidental, or consequential damages of any character arising as a
160+
result of this License or out of the use or inability to use the
161+
Work (including but not limited to damages for loss of goodwill,
162+
work stoppage, computer failure or malfunction, or any and all
163+
other commercial damages or losses), even if such Contributor
164+
has been advised of the possibility of such damages.
165+
166+
9. Accepting Warranty or Support. When redistributing the Work or
167+
Derivative Works thereof, You may choose to offer, and charge a fee
168+
for, acceptance of support, warranty, indemnity, or other liability
169+
obligations and/or rights consistent with this License. However, in
170+
accepting such obligations, You may act only on Your own behalf and on
171+
Your sole responsibility, not on behalf of any other Contributor, and
172+
only if You agree to indemnify, defend, and hold each Contributor
173+
harmless for any liability incurred by, or claims asserted against,
174+
such Contributor by reason of your accepting any such warranty or support.
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 [yyyy] [name of copyright owner]
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.
Lines changed: 27 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,121 +1,50 @@
11
OpenTelemetry OpenAI Agents Instrumentation
22
==========================================
33

4-
This package instruments OpenAI agent frameworks ("openai-agents") and forwards spans
5-
into OpenTelemetry using the draft GenAI semantic conventions proposed upstream in
6-
OpenTelemetry Semantic Conventions PR 2528_ (subject to change until stabilized).
4+
|pypi|
75

8-
Status: Experimental / Alpha
6+
.. |pypi| image:: https://badge.fury.io/py/opentelemetry-instrumentation-openai-agents.svg
7+
:target: https://pypi.org/project/opentelemetry-instrumentation-openai-agents/
98

10-
What You Get
9+
This library allows tracing OpenAI Agents framework requests and logging of messages made by the
10+
`OpenAI Python API library <https://pypi.org/project/openai/>`_ when used with agent frameworks.
11+
It also captures the duration of the operations and the number of tokens used as metrics.
12+
13+
Installation
1114
------------
12-
This instrumentation wires the OpenAI Agents (``openai-agents``) tracing hook into
13-
OpenTelemetry and maps agent / tool / response span data to the draft GenAI
14-
semantic conventions shipped alongside this package. It currently provides:
15-
16-
* Span kinds & names for ``create_agent``, ``invoke_agent``, ``execute_tool``, ``chat`` (responses), ``embeddings`` (when available)
17-
* Core request attributes: model, max_tokens, temperature, top_p, top_k, penalties, stop sequences, seed, encoding formats
18-
* Choice count (``gen_ai.request.choice.count``) when ``n``/``choice_count`` > 1
19-
* Output type (``gen_ai.output.type``) from ``response_format.type``
20-
* Response attributes: id, model, aggregated finish reasons
21-
* Token usage (input/prompt + output/completion) from both span data or response object
22-
* OpenAI specific: request / response service tier, system fingerprint
23-
* Server endpoint host/port extraction (``server.address`` / ``server.port``)
24-
* Conversation / thread id (``gen_ai.conversation.id``)
25-
* Agent metadata: id, name, description
26-
* Tool metadata: name, id, type, description; tool call arguments & results (opt‑in)
27-
* Tool definitions (opt‑in) & orchestrator agent definitions
28-
* Data source id for retrieval / RAG scenarios
29-
* Optional input / output message capture with truncation
30-
- Messages are serialized to JSON strings (instead of raw lists of dicts) to comply with OpenTelemetry attribute type requirements and avoid exporter warnings.
31-
* Events: user / assistant / tool messages, tool call + tool result, per-choice events
32-
* Metrics (duration + token usage histograms) behind an env toggle
33-
* Size guarding via JSON serialization + max length truncation (default 20 KB)
15+
16+
::
17+
18+
pip install opentelemetry-instrumentation-openai-agents
3419

3520
Usage
3621
-----
22+
3723
.. code:: python
3824
3925
from openai import OpenAI
4026
from opentelemetry.instrumentation.openai_agents import OpenAIAgentsInstrumentor
4127
4228
OpenAIAgentsInstrumentor().instrument()
43-
client = OpenAI()
44-
# run your agent framework (openai-agents) code
45-
46-
Configuration (Environment Variables)
47-
-------------------------------------
48-
Set these before importing / enabling instrumentation:
49-
50-
* ``OTEL_INSTRUMENTATION_OPENAI_AGENTS_CAPTURE_CONTENT`` (default ``false``)
51-
- When ``true`` records ``gen_ai.input.messages`` + ``gen_ai.output.messages`` and emits message events.
52-
* ``OTEL_INSTRUMENTATION_OPENAI_AGENTS_CAPTURE_TOOL_DEFINITIONS`` (default ``false``)
53-
- When ``true`` records ``gen_ai.tool.definitions`` (can be large & sensitive).
54-
* ``OTEL_INSTRUMENTATION_OPENAI_AGENTS_CAPTURE_TOOL_IO`` (default ``false``)
55-
- When ``true`` records tool call arguments / results & emits assistant/tool message events.
56-
* ``OTEL_INSTRUMENTATION_OPENAI_AGENTS_CAPTURE_METRICS`` (default ``true``)
57-
- Set to ``false`` to disable ``gen_ai.operation.duration`` and ``gen_ai.token.usage`` histograms.
58-
* ``OTEL_INSTRUMENTATION_OPENAI_AGENTS_MAX_VALUE_LENGTH`` (default ``20480``)
59-
- Max serialized length for large attribute values (tool defs, messages, arguments, results). Values exceeding are truncated with ``...``.
60-
61-
Security & PII Note: Content, tool IO, and tool definitions may contain sensitive data. Leave toggles off in production unless required.
62-
63-
Metrics
64-
-------
65-
When metrics are enabled the following histograms are recorded:
66-
67-
* ``gen_ai.operation.duration`` (seconds) - per span operation duration.
68-
* ``gen_ai.token.usage`` (tokens) - one data point per input/output token count with attribute ``gen_ai.token.type`` = ``input`` or ``output``.
69-
70-
Both include low‑cardinality attributes: ``gen_ai.provider.name``, ``gen_ai.operation.name``, and ``gen_ai.request.model`` (if available). Errors add ``error.type``.
71-
72-
Exporting to Azure Application Insights
73-
---------------------------------------
74-
Use the OpenTelemetry Azure Monitor exporter in your app:
75-
76-
.. code:: python
77-
78-
from azure.monitor.opentelemetry import configure_azure_monitor
79-
80-
configure_azure_monitor(
81-
connection_string="InstrumentationKey=...;IngestionEndpoint=..."
82-
)
83-
84-
from opentelemetry.instrumentation.openai_agents import OpenAIAgentsInstrumentor
85-
OpenAIAgentsInstrumentor().instrument()
86-
87-
# start your agent workflow
8829
89-
The exporter will ship the agent / tool / model invocation spans with attributes
90-
outlined in the upstream semantic conventions (see PR 2528_) (create_agent, invoke_agent,
91-
execute_tool, etc.).
30+
# Your OpenAI agents code here
31+
client = OpenAI()
9232
93-
Truncation Strategy
94-
-------------------
95-
Large structured values are JSON serialized and truncated to the configured byte length (default 20480). This affects: tool definitions, tool arguments/results, input/output messages, orchestrator agent definitions. Truncation preserves valid UTF‑8 boundaries by operating on Python strings (code points) before final attribute assignment.
33+
API
34+
---
9635

97-
Limitations & Future Work
98-
-------------------------
99-
* No explicit instrumentation for streaming chunk events yet (would require upstream hooks) — intentionally deferred.
100-
* Draft semantic conventions may evolve; attribute names could change before stabilization. When the schema version updates, re‑validate against the upstream semantic conventions (see PR 2528_).
101-
* Extended test coverage is growing; please add cases when introducing new span data types or attributes (see existing tests for patterns).
36+
The `opentelemetry-instrumentation-openai-agents` package provides automatic instrumentation for the OpenAI Agents framework.
10237

103-
Removed Previous Limitations
104-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
105-
The following earlier limitations have been addressed:
38+
Configuration
39+
-------------
10640

107-
* Deactivation: ``uninstrument()`` now calls processor ``shutdown()`` which prevents new spans and ends any open ones.
108-
* Operation naming: ``create_agent`` vs ``invoke_agent`` now prefers an explicit upstream flag (``is_creation``) and falls back to a refined heuristic (no parent + description implies creation).
109-
* Additional span types (embeddings, transcription, speech, guardrail, handoff) are recognized with stable operation names.
110-
* Metrics, truncation, tool IO/content gating all implemented and configurable.
111-
* Time handling uses timezone-aware UTC timestamps; no deprecated ``datetime.utcnow`` usage.
41+
The following environment variables can be used to configure the instrumentation:
11242

113-
Contributing
114-
------------
115-
Please add tests when extending attribute coverage or events. Keep attribute cardinality low for metrics. Avoid capturing content unless explicitly gated by an env var.
43+
- ``OTEL_INSTRUMENTATION_OPENAI_AGENTS_CAPTURE_CONTENT``: Set to ``true`` to capture the content of the requests and responses. Default is ``false``.
44+
- ``OTEL_INSTRUMENTATION_OPENAI_AGENTS_CAPTURE_METRICS``: Set to ``true`` to capture metrics. Default is ``true``.
11645

117-
License
118-
-------
119-
Apache 2.0
46+
References
47+
----------
12048

121-
.. _2528: https://github.com/open-telemetry/semantic-conventions/pull/2528
49+
* `OpenTelemetry Project <https://opentelemetry.io/>`_
50+
* `OpenAI Python API Library <https://pypi.org/project/openai/>`_

0 commit comments

Comments
 (0)