@loongsuite/otel-util-genai 0.1.0-beta.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.
Files changed (103) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +262 -0
  3. package/dist/environment-variables.d.ts +8 -0
  4. package/dist/environment-variables.d.ts.map +1 -0
  5. package/dist/environment-variables.js +21 -0
  6. package/dist/environment-variables.js.map +1 -0
  7. package/dist/event-log/converter.d.ts +19 -0
  8. package/dist/event-log/converter.d.ts.map +1 -0
  9. package/dist/event-log/converter.js +216 -0
  10. package/dist/event-log/converter.js.map +1 -0
  11. package/dist/event-log/field-mapping.d.ts +53 -0
  12. package/dist/event-log/field-mapping.d.ts.map +1 -0
  13. package/dist/event-log/field-mapping.js +400 -0
  14. package/dist/event-log/field-mapping.js.map +1 -0
  15. package/dist/event-log/grouping.d.ts +67 -0
  16. package/dist/event-log/grouping.d.ts.map +1 -0
  17. package/dist/event-log/grouping.js +241 -0
  18. package/dist/event-log/grouping.js.map +1 -0
  19. package/dist/event-log/index.d.ts +5 -0
  20. package/dist/event-log/index.d.ts.map +1 -0
  21. package/dist/event-log/index.js +18 -0
  22. package/dist/event-log/index.js.map +1 -0
  23. package/dist/event-log/parent-context.d.ts +14 -0
  24. package/dist/event-log/parent-context.d.ts.map +1 -0
  25. package/dist/event-log/parent-context.js +45 -0
  26. package/dist/event-log/parent-context.js.map +1 -0
  27. package/dist/event-log/readable-spans.d.ts +36 -0
  28. package/dist/event-log/readable-spans.d.ts.map +1 -0
  29. package/dist/event-log/readable-spans.js +73 -0
  30. package/dist/event-log/readable-spans.js.map +1 -0
  31. package/dist/event-log/types.d.ts +78 -0
  32. package/dist/event-log/types.d.ts.map +1 -0
  33. package/dist/event-log/types.js +35 -0
  34. package/dist/event-log/types.js.map +1 -0
  35. package/dist/extended-environment-variables.d.ts +12 -0
  36. package/dist/extended-environment-variables.d.ts.map +1 -0
  37. package/dist/extended-environment-variables.js +25 -0
  38. package/dist/extended-environment-variables.js.map +1 -0
  39. package/dist/extended-handler.d.ts +50 -0
  40. package/dist/extended-handler.d.ts.map +1 -0
  41. package/dist/extended-handler.js +334 -0
  42. package/dist/extended-handler.js.map +1 -0
  43. package/dist/extended-metrics.d.ts +13 -0
  44. package/dist/extended-metrics.d.ts.map +1 -0
  45. package/dist/extended-metrics.js +27 -0
  46. package/dist/extended-metrics.js.map +1 -0
  47. package/dist/extended-span-utils.d.ts +14 -0
  48. package/dist/extended-span-utils.d.ts.map +1 -0
  49. package/dist/extended-span-utils.js +427 -0
  50. package/dist/extended-span-utils.js.map +1 -0
  51. package/dist/extended-types.d.ts +150 -0
  52. package/dist/extended-types.d.ts.map +1 -0
  53. package/dist/extended-types.js +46 -0
  54. package/dist/extended-types.js.map +1 -0
  55. package/dist/handler.d.ts +23 -0
  56. package/dist/handler.d.ts.map +1 -0
  57. package/dist/handler.js +127 -0
  58. package/dist/handler.js.map +1 -0
  59. package/dist/index.d.ts +22 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +43 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/instruments.d.ts +4 -0
  64. package/dist/instruments.d.ts.map +1 -0
  65. package/dist/instruments.js +37 -0
  66. package/dist/instruments.js.map +1 -0
  67. package/dist/memory/memory-types.d.ts +26 -0
  68. package/dist/memory/memory-types.d.ts.map +1 -0
  69. package/dist/memory/memory-types.js +17 -0
  70. package/dist/memory/memory-types.js.map +1 -0
  71. package/dist/memory/memory-utils.d.ts +7 -0
  72. package/dist/memory/memory-utils.d.ts.map +1 -0
  73. package/dist/memory/memory-utils.js +121 -0
  74. package/dist/memory/memory-utils.js.map +1 -0
  75. package/dist/metrics.d.ts +11 -0
  76. package/dist/metrics.d.ts.map +1 -0
  77. package/dist/metrics.js +77 -0
  78. package/dist/metrics.js.map +1 -0
  79. package/dist/semconv/gen-ai-extended-attributes.d.ts +101 -0
  80. package/dist/semconv/gen-ai-extended-attributes.d.ts.map +1 -0
  81. package/dist/semconv/gen-ai-extended-attributes.js +120 -0
  82. package/dist/semconv/gen-ai-extended-attributes.js.map +1 -0
  83. package/dist/semconv/gen-ai-memory-attributes.d.ts +28 -0
  84. package/dist/semconv/gen-ai-memory-attributes.d.ts.map +1 -0
  85. package/dist/semconv/gen-ai-memory-attributes.js +42 -0
  86. package/dist/semconv/gen-ai-memory-attributes.js.map +1 -0
  87. package/dist/span-utils.d.ts +18 -0
  88. package/dist/span-utils.d.ts.map +1 -0
  89. package/dist/span-utils.js +236 -0
  90. package/dist/span-utils.js.map +1 -0
  91. package/dist/types.d.ts +117 -0
  92. package/dist/types.d.ts.map +1 -0
  93. package/dist/types.js +33 -0
  94. package/dist/types.js.map +1 -0
  95. package/dist/utils.d.ts +8 -0
  96. package/dist/utils.d.ts.map +1 -0
  97. package/dist/utils.js +88 -0
  98. package/dist/utils.js.map +1 -0
  99. package/dist/version.d.ts +2 -0
  100. package/dist/version.d.ts.map +1 -0
  101. package/dist/version.js +2 -0
  102. package/dist/version.js.map +1 -0
  103. package/package.json +72 -0
package/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 [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.
package/README.md ADDED
@@ -0,0 +1,262 @@
1
+ # @loongsuite/otel-util-genai
2
+
3
+ OpenTelemetry GenAI utility library for Node.js — standardized telemetry collection for Generative AI operations including LLM, Agent, Embedding, Tool, Retrieval, Rerank, Memory, Entry, and ReAct Step.
4
+
5
+ This is the Node.js equivalent of the Python `opentelemetry-util-genai` package, following the same semantic conventions and API design patterns.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @loongsuite/otel-util-genai
11
+ ```
12
+
13
+ ## Features
14
+
15
+ - **LLM (Chat/Completion)**: Track LLM requests with full message content, token usage, and streaming TTFT
16
+ - **Agent**: Create and invoke agents with tool definitions and conversation context
17
+ - **Embedding**: Monitor embedding generation with dimension counts and encoding formats
18
+ - **Tool Execution**: Trace tool calls with arguments and results
19
+ - **Retrieval**: Observe document retrieval from vector stores with query and results
20
+ - **Rerank**: Track document reranking operations with scoring details
21
+ - **Memory**: Record memory operations (add, search, update, delete, etc.)
22
+ - **Entry**: Mark AI application system entry points with session/user context
23
+ - **ReAct Step**: Track individual Reasoning-Acting iterations in agents
24
+
25
+ ## Quick Start
26
+
27
+ ### Using TelemetryHandler (LLM only)
28
+
29
+ ```typescript
30
+ import {
31
+ TelemetryHandler,
32
+ createLLMInvocation,
33
+ } from "@loongsuite/otel-util-genai";
34
+
35
+ const handler = new TelemetryHandler();
36
+
37
+ // Callback pattern (recommended)
38
+ await handler.llm(
39
+ createLLMInvocation({
40
+ requestModel: "gpt-4",
41
+ provider: "openai",
42
+ inputMessages: [
43
+ { role: "user", parts: [{ type: "text", content: "Hello!" }] },
44
+ ],
45
+ }),
46
+ async (inv) => {
47
+ // Call your LLM API here...
48
+ inv.outputMessages = [
49
+ {
50
+ role: "assistant",
51
+ parts: [{ type: "text", content: "Hi there!" }],
52
+ finishReason: "stop",
53
+ },
54
+ ];
55
+ inv.inputTokens = 5;
56
+ inv.outputTokens = 10;
57
+ },
58
+ );
59
+
60
+ // Or manual start/stop pattern
61
+ const inv = createLLMInvocation({ requestModel: "gpt-4", provider: "openai" });
62
+ handler.startLlm(inv);
63
+ try {
64
+ // Call your LLM API...
65
+ inv.inputTokens = 5;
66
+ inv.outputTokens = 10;
67
+ handler.stopLlm(inv);
68
+ } catch (err) {
69
+ handler.failLlm(inv, {
70
+ message: String(err),
71
+ type: err instanceof Error ? err.constructor.name : "Error",
72
+ });
73
+ }
74
+ ```
75
+
76
+ ### Using ExtendedTelemetryHandler (All operations)
77
+
78
+ ```typescript
79
+ import {
80
+ ExtendedTelemetryHandler,
81
+ createEmbeddingInvocation,
82
+ createRetrievalInvocation,
83
+ createInvokeAgentInvocation,
84
+ createMemoryInvocation,
85
+ } from "@loongsuite/otel-util-genai";
86
+
87
+ const handler = new ExtendedTelemetryHandler();
88
+
89
+ // Embedding
90
+ handler.embedding(
91
+ createEmbeddingInvocation("text-embedding-3-small"),
92
+ (inv) => {
93
+ inv.inputTokens = 100;
94
+ inv.dimensionCount = 1536;
95
+ },
96
+ );
97
+
98
+ // Retrieval
99
+ handler.retrieval(
100
+ createRetrievalInvocation({ dataSourceId: "my_vector_store", topK: 5 }),
101
+ (inv) => {
102
+ inv.documents = [
103
+ { id: "doc1", score: 0.95, content: "..." },
104
+ { id: "doc2", score: 0.87, content: "..." },
105
+ ];
106
+ },
107
+ );
108
+
109
+ // Agent
110
+ await handler.invokeAgent(
111
+ createInvokeAgentInvocation("openai", { agentName: "research-agent" }),
112
+ async (inv) => {
113
+ // ... agent invocation
114
+ inv.inputTokens = 500;
115
+ inv.outputTokens = 200;
116
+ },
117
+ );
118
+
119
+ // Memory
120
+ handler.memory(createMemoryInvocation("search", { userId: "user-1" }), (inv) => {
121
+ inv.outputMessages = [{ content: "remembered context" }];
122
+ });
123
+ ```
124
+
125
+ ## Environment Variables
126
+
127
+ | Variable | Description | Default |
128
+ |---|---|---|
129
+ | `OTEL_SEMCONV_STABILITY_OPT_IN` | Set to `gen_ai_latest_experimental` to enable experimental features | - |
130
+ | `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` | Content capturing mode: `NO_CONTENT`, `SPAN_ONLY`, `EVENT_ONLY`, `SPAN_AND_EVENT` | `NO_CONTENT` |
131
+ | `OTEL_INSTRUMENTATION_GENAI_EMIT_EVENT` | Whether to emit `gen_ai.client.inference.operation.details` events: `true`/`false` | Based on content mode |
132
+
133
+ ## Supported Operation Types
134
+
135
+ | Operation | Span Kind | `gen_ai.operation.name` | Handler Method |
136
+ |---|---|---|---|
137
+ | LLM Chat | LLM | `chat` | `llm()` / `startLlm()` |
138
+ | Create Agent | AGENT | `create_agent` | `createAgent()` / `startCreateAgent()` |
139
+ | Invoke Agent | AGENT | `invoke_agent` | `invokeAgent()` / `startInvokeAgent()` |
140
+ | Embedding | EMBEDDING | `embeddings` | `embedding()` / `startEmbedding()` |
141
+ | Execute Tool | TOOL | `execute_tool` | `executeTool()` / `startExecuteTool()` |
142
+ | Retrieval | RETRIEVER | `retrieval` | `retrieval()` / `startRetrieval()` |
143
+ | Rerank | RERANKER | `rerank_documents` | `rerank()` / `startRerank()` |
144
+ | Memory | MEMORY | `memory_operation` | `memory()` / `startMemory()` |
145
+ | Entry | ENTRY | `enter` | `entry()` / `startEntry()` |
146
+ | ReAct Step | STEP | `react` | `reactStep()` / `startReactStep()` |
147
+
148
+ ## Semantic Conventions
149
+
150
+ This library follows the [OpenTelemetry GenAI Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) with LoongSuite extensions for:
151
+
152
+ - `gen_ai.span.kind` — Logical span kind classification
153
+ - Extended operation names (`retrieval`, `rerank_documents`, `enter`, `react`)
154
+ - Memory operation attributes (`gen_ai.memory.*`)
155
+ - Cache token usage (`gen_ai.usage.cache_creation.input_tokens`, `gen_ai.usage.cache_read.input_tokens`)
156
+ - Total token calculation (`gen_ai.usage.total_tokens`)
157
+ - Time to first token (`gen_ai.response.time_to_first_token`)
158
+
159
+ ## API Reference
160
+
161
+ ### Core Classes
162
+
163
+ - **`TelemetryHandler`** — Manages LLM invocation lifecycles with span, metrics, and event emission
164
+ - **`ExtendedTelemetryHandler`** — Extends `TelemetryHandler` with support for all GenAI operation types
165
+
166
+ ### Factory Functions
167
+
168
+ - `createLLMInvocation(init?)` — Create an LLM invocation with defaults
169
+ - `createEmbeddingInvocation(requestModel, init?)` — Create an embedding invocation
170
+ - `createExecuteToolInvocation(toolName, init?)` — Create a tool execution invocation
171
+ - `createCreateAgentInvocation(provider, init?)` — Create an agent creation invocation
172
+ - `createInvokeAgentInvocation(provider, init?)` — Create an agent invocation
173
+ - `createRetrievalInvocation(init?)` — Create a retrieval invocation
174
+ - `createRerankInvocation(provider, init?)` — Create a rerank invocation
175
+ - `createMemoryInvocation(operation, init?)` — Create a memory invocation
176
+ - `createEntryInvocation(init?)` — Create an entry invocation
177
+ - `createReactStepInvocation(init?)` — Create a ReAct step invocation
178
+
179
+ ### Singleton Accessors
180
+
181
+ - `getTelemetryHandler(options?)` — Get or create the default `TelemetryHandler`
182
+ - `getExtendedTelemetryHandler(options?)` — Get or create the default `ExtendedTelemetryHandler`
183
+
184
+ ## Event Log → Trace conversion
185
+
186
+ The package can convert a flat list of records that follow the
187
+ [loongsuite-pilot AI event schema](https://github.com/alibaba/loongsuite-pilot)
188
+ into an OTel span tree (`ENTRY → AGENT → STEP → LLM/TOOL`) that satisfies the
189
+ ARMS GenAI semantic conventions. This lets agent plugins keep emitting only
190
+ event logs and delegate trace shape to this SDK.
191
+
192
+ ```ts
193
+ import { readFileSync } from "node:fs";
194
+ import {
195
+ BasicTracerProvider,
196
+ BatchSpanProcessor,
197
+ } from "@opentelemetry/sdk-trace-base";
198
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
199
+ import {
200
+ ExtendedTelemetryHandler,
201
+ convertEventLogToTrace,
202
+ } from "@loongsuite/otel-util-genai";
203
+
204
+ const provider = new BasicTracerProvider({
205
+ spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter())],
206
+ });
207
+ const handler = new ExtendedTelemetryHandler({ tracerProvider: provider });
208
+
209
+ const records = JSON.parse(readFileSync("turn-events.json", "utf-8"));
210
+ const { traceIds, spanCount, warnings } = convertEventLogToTrace(records, {
211
+ handler,
212
+ strict: false,
213
+ });
214
+ await provider.forceFlush();
215
+
216
+ console.log(`Exported ${spanCount} spans across ${traceIds.length} traces`);
217
+ if (warnings.length) console.warn(warnings);
218
+ ```
219
+
220
+ ### Helper: returning `ReadableSpan[]` directly
221
+
222
+ If you don't already own a TracerProvider — for example you're building a
223
+ downstream pilot/exporter that needs the span data as values to feed into
224
+ your own `OTLPTraceExporter` — use the helper:
225
+
226
+ ```ts
227
+ import { convertEventLogToReadableSpans } from "@loongsuite/otel-util-genai";
228
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
229
+
230
+ const exporter = new OTLPTraceExporter({ url, headers });
231
+ const { spans, traceIds, warnings } = await convertEventLogToReadableSpans(records);
232
+ exporter.export(spans, (result) => {
233
+ if (result.code !== 0) console.error("export failed", result.error);
234
+ });
235
+ ```
236
+
237
+ The helper internally spins up a private `BasicTracerProvider` +
238
+ `InMemorySpanExporter`, runs the conversion, captures finished spans, and
239
+ tears the provider down. It is never registered globally, so it cannot
240
+ pollute the host process's OTel context. Requires
241
+ `@opentelemetry/sdk-trace-base` at runtime (declared as an optional peer
242
+ dep — install it in the consumer package).
243
+
244
+ ### Behavior summary
245
+
246
+ - Records are grouped by `gen_ai.turn.id` (one OTel trace per turn) then by
247
+ `gen_ai.step.id` (one STEP span per step).
248
+ - Each `llm.request` + `llm.response` pair becomes one LLM span; each
249
+ `tool.call` + `tool.result` pair becomes one TOOL span.
250
+ - `trace_id` on the records is honored — generated spans inherit it via a
251
+ synthetic parent context. If `trace_id` is missing the SDK allocates one.
252
+ - `gen_ai.input.messages_delta` is accumulated across the whole turn to
253
+ reconstruct full `gen_ai.input.messages` for each LLM span.
254
+ - `strict: true` throws `EventLogConversionError` on the first issue;
255
+ otherwise non-fatal problems are returned in `warnings`.
256
+
257
+ For downstream consumers (e.g. loongsuite-pilot's OTLP trace flusher), see
258
+ [`PILOT_INTEGRATION.md`](./PILOT_INTEGRATION.md) for a full walkthrough.
259
+
260
+ ## License
261
+
262
+ Apache License 2.0
@@ -0,0 +1,8 @@
1
+ export declare const OTEL_SEMCONV_STABILITY_OPT_IN = "OTEL_SEMCONV_STABILITY_OPT_IN";
2
+ export declare const OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT";
3
+ export declare const OTEL_INSTRUMENTATION_GENAI_EMIT_EVENT = "OTEL_INSTRUMENTATION_GENAI_EMIT_EVENT";
4
+ export declare const OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK = "OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK";
5
+ export declare const OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH = "OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH";
6
+ export declare const OTEL_INSTRUMENTATION_GENAI_UPLOAD_FORMAT = "OTEL_INSTRUMENTATION_GENAI_UPLOAD_FORMAT";
7
+ export declare const OTEL_INSTRUMENTATION_GENAI_UPLOAD_MAX_QUEUE_SIZE = "OTEL_INSTRUMENTATION_GENAI_UPLOAD_MAX_QUEUE_SIZE";
8
+ //# sourceMappingURL=environment-variables.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environment-variables.d.ts","sourceRoot":"","sources":["../src/environment-variables.ts"],"names":[],"mappings":"AAcA,eAAO,MAAM,6BAA6B,kCAAkC,CAAC;AAC7E,eAAO,MAAM,kDAAkD,uDACT,CAAC;AACvD,eAAO,MAAM,qCAAqC,0CACT,CAAC;AAC1C,eAAO,MAAM,0CAA0C,+CACT,CAAC;AAC/C,eAAO,MAAM,2CAA2C,gDACT,CAAC;AAChD,eAAO,MAAM,wCAAwC,6CACT,CAAC;AAC7C,eAAO,MAAM,gDAAgD,qDACT,CAAC"}
@@ -0,0 +1,21 @@
1
+ // Copyright The OpenTelemetry Authors
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ export const OTEL_SEMCONV_STABILITY_OPT_IN = "OTEL_SEMCONV_STABILITY_OPT_IN";
15
+ export const OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT";
16
+ export const OTEL_INSTRUMENTATION_GENAI_EMIT_EVENT = "OTEL_INSTRUMENTATION_GENAI_EMIT_EVENT";
17
+ export const OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK = "OTEL_INSTRUMENTATION_GENAI_COMPLETION_HOOK";
18
+ export const OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH = "OTEL_INSTRUMENTATION_GENAI_UPLOAD_BASE_PATH";
19
+ export const OTEL_INSTRUMENTATION_GENAI_UPLOAD_FORMAT = "OTEL_INSTRUMENTATION_GENAI_UPLOAD_FORMAT";
20
+ export const OTEL_INSTRUMENTATION_GENAI_UPLOAD_MAX_QUEUE_SIZE = "OTEL_INSTRUMENTATION_GENAI_UPLOAD_MAX_QUEUE_SIZE";
21
+ //# sourceMappingURL=environment-variables.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"environment-variables.js","sourceRoot":"","sources":["../src/environment-variables.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,EAAE;AACF,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,iDAAiD;AACjD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,MAAM,CAAC,MAAM,6BAA6B,GAAG,+BAA+B,CAAC;AAC7E,MAAM,CAAC,MAAM,kDAAkD,GAC7D,oDAAoD,CAAC;AACvD,MAAM,CAAC,MAAM,qCAAqC,GAChD,uCAAuC,CAAC;AAC1C,MAAM,CAAC,MAAM,0CAA0C,GACrD,4CAA4C,CAAC;AAC/C,MAAM,CAAC,MAAM,2CAA2C,GACtD,6CAA6C,CAAC;AAChD,MAAM,CAAC,MAAM,wCAAwC,GACnD,0CAA0C,CAAC;AAC7C,MAAM,CAAC,MAAM,gDAAgD,GAC3D,kDAAkD,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { type ConvertOptions, type ConvertResult, type EventLogRecord } from "./types.js";
2
+ export { EventName } from "./types.js";
3
+ /**
4
+ * Convert a flat event log into OTel spans using the supplied handler.
5
+ *
6
+ * Span hierarchy produced per turn (matches ARMS GenAI semantic conventions):
7
+ *
8
+ * ENTRY
9
+ * └── AGENT
10
+ * └── STEP (one per gen_ai.step.id)
11
+ * ├── LLM (one per llm.request+llm.response pair)
12
+ * └── TOOL (one per tool.call+tool.result pair)
13
+ *
14
+ * trace_id from the event log is honored — all spans of a turn inherit it via
15
+ * a synthetic parent SpanContext. If trace_id is missing or invalid, the SDK
16
+ * allocates a fresh one.
17
+ */
18
+ export declare function convertEventLogToTrace(records: EventLogRecord[], options?: ConvertOptions): ConvertResult;
19
+ //# sourceMappingURL=converter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"converter.d.ts","sourceRoot":"","sources":["../../src/event-log/converter.ts"],"names":[],"mappings":"AAiBA,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,cAAc,EAKpB,MAAM,YAAY,CAAC;AAsBpB,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,cAAc,EAAE,EACzB,OAAO,CAAC,EAAE,cAAc,GACvB,aAAa,CA4Bf"}