@introspection-sdk/introspection-node 0.20.0 → 0.21.1

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 (211) hide show
  1. package/README.md +28 -8
  2. package/dist/auth.d.ts +1 -1
  3. package/dist/client.d.ts +4 -3
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/client.js +16 -7
  6. package/dist/client.js.map +1 -1
  7. package/dist/dev-target.js +1 -1
  8. package/dist/index.d.ts +3 -7
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +2 -6
  11. package/dist/index.js.map +1 -1
  12. package/dist/otel/index.d.ts +1 -14
  13. package/dist/otel/index.d.ts.map +1 -1
  14. package/dist/otel/index.js +10 -18
  15. package/dist/otel/index.js.map +1 -1
  16. package/dist/otel/init.d.ts +19 -21
  17. package/dist/otel/init.d.ts.map +1 -1
  18. package/dist/otel/init.js +62 -48
  19. package/dist/otel/init.js.map +1 -1
  20. package/dist/otel/integrations/base.d.ts +17 -37
  21. package/dist/otel/integrations/base.d.ts.map +1 -1
  22. package/dist/otel/integrations/base.js +6 -13
  23. package/dist/otel/integrations/base.js.map +1 -1
  24. package/dist/otel/integrations/index.d.ts +3 -4
  25. package/dist/otel/integrations/index.d.ts.map +1 -1
  26. package/dist/otel/integrations/index.js +6 -25
  27. package/dist/otel/integrations/index.js.map +1 -1
  28. package/dist/otel/integrations/pi.d.ts.map +1 -1
  29. package/dist/otel/integrations/pi.js +9 -1
  30. package/dist/otel/integrations/pi.js.map +1 -1
  31. package/dist/otel/logs.d.ts +41 -8
  32. package/dist/otel/logs.d.ts.map +1 -1
  33. package/dist/otel/logs.js +95 -66
  34. package/dist/otel/logs.js.map +1 -1
  35. package/dist/otel/pi.d.ts +18 -5
  36. package/dist/otel/pi.d.ts.map +1 -1
  37. package/dist/otel/pi.js +38 -9
  38. package/dist/otel/pi.js.map +1 -1
  39. package/dist/otel/register.d.ts +2 -2
  40. package/dist/otel/register.d.ts.map +1 -1
  41. package/dist/otel/register.js +7 -9
  42. package/dist/otel/register.js.map +1 -1
  43. package/dist/otel/setup.d.ts +2 -2
  44. package/dist/otel/setup.d.ts.map +1 -1
  45. package/dist/otel/setup.js +16 -6
  46. package/dist/otel/setup.js.map +1 -1
  47. package/dist/otel/span-processor.d.ts +18 -5
  48. package/dist/otel/span-processor.d.ts.map +1 -1
  49. package/dist/otel/span-processor.js +50 -65
  50. package/dist/otel/span-processor.js.map +1 -1
  51. package/dist/resources/experiments.d.ts +10 -5
  52. package/dist/resources/experiments.d.ts.map +1 -1
  53. package/dist/resources/experiments.js +9 -25
  54. package/dist/resources/experiments.js.map +1 -1
  55. package/dist/resources/recipes.d.ts +6 -6
  56. package/dist/resources/recipes.d.ts.map +1 -1
  57. package/dist/resources/recipes.js +5 -23
  58. package/dist/resources/recipes.js.map +1 -1
  59. package/dist/resources/runtimes.d.ts +2 -2
  60. package/dist/resources/runtimes.d.ts.map +1 -1
  61. package/dist/resources/runtimes.js +2 -2
  62. package/dist/resources/runtimes.js.map +1 -1
  63. package/dist/runner.d.ts +8 -4
  64. package/dist/runner.d.ts.map +1 -1
  65. package/dist/runner.js +26 -18
  66. package/dist/runner.js.map +1 -1
  67. package/dist/types.d.ts +1 -1
  68. package/dist/types.d.ts.map +1 -1
  69. package/dist/types.js +1 -1
  70. package/dist/types.js.map +1 -1
  71. package/dist/utils.d.ts +45 -0
  72. package/dist/utils.d.ts.map +1 -1
  73. package/dist/utils.js +61 -2
  74. package/dist/utils.js.map +1 -1
  75. package/dist/version.d.ts +1 -1
  76. package/dist/version.d.ts.map +1 -1
  77. package/dist/version.js +1 -1
  78. package/dist/version.js.map +1 -1
  79. package/package.json +16 -58
  80. package/.turbo/turbo-build.log +0 -4
  81. package/dist/converters/claude.d.ts +0 -150
  82. package/dist/converters/claude.d.ts.map +0 -1
  83. package/dist/converters/claude.js +0 -211
  84. package/dist/converters/claude.js.map +0 -1
  85. package/dist/converters/gemini.d.ts +0 -90
  86. package/dist/converters/gemini.d.ts.map +0 -1
  87. package/dist/converters/gemini.js +0 -171
  88. package/dist/converters/gemini.js.map +0 -1
  89. package/dist/converters/index.d.ts +0 -9
  90. package/dist/converters/index.d.ts.map +0 -1
  91. package/dist/converters/index.js +0 -9
  92. package/dist/converters/index.js.map +0 -1
  93. package/dist/converters/openai.d.ts +0 -51
  94. package/dist/converters/openai.d.ts.map +0 -1
  95. package/dist/converters/openai.js +0 -269
  96. package/dist/converters/openai.js.map +0 -1
  97. package/dist/converters/openinference.d.ts +0 -107
  98. package/dist/converters/openinference.d.ts.map +0 -1
  99. package/dist/converters/openinference.js +0 -553
  100. package/dist/converters/openinference.js.map +0 -1
  101. package/dist/converters/vercel.d.ts +0 -21
  102. package/dist/converters/vercel.d.ts.map +0 -1
  103. package/dist/converters/vercel.js +0 -236
  104. package/dist/converters/vercel.js.map +0 -1
  105. package/dist/otel/anthropic.d.ts +0 -63
  106. package/dist/otel/anthropic.d.ts.map +0 -1
  107. package/dist/otel/anthropic.js +0 -475
  108. package/dist/otel/anthropic.js.map +0 -1
  109. package/dist/otel/claude-hooks.d.ts +0 -346
  110. package/dist/otel/claude-hooks.d.ts.map +0 -1
  111. package/dist/otel/claude-hooks.js +0 -647
  112. package/dist/otel/claude-hooks.js.map +0 -1
  113. package/dist/otel/claude-wrapper.d.ts +0 -93
  114. package/dist/otel/claude-wrapper.d.ts.map +0 -1
  115. package/dist/otel/claude-wrapper.js +0 -155
  116. package/dist/otel/claude-wrapper.js.map +0 -1
  117. package/dist/otel/gemini.d.ts +0 -56
  118. package/dist/otel/gemini.d.ts.map +0 -1
  119. package/dist/otel/gemini.js +0 -350
  120. package/dist/otel/gemini.js.map +0 -1
  121. package/dist/otel/integrations/anthropic.d.ts +0 -10
  122. package/dist/otel/integrations/anthropic.d.ts.map +0 -1
  123. package/dist/otel/integrations/anthropic.js +0 -26
  124. package/dist/otel/integrations/anthropic.js.map +0 -1
  125. package/dist/otel/integrations/claude-agent.d.ts +0 -12
  126. package/dist/otel/integrations/claude-agent.d.ts.map +0 -1
  127. package/dist/otel/integrations/claude-agent.js +0 -28
  128. package/dist/otel/integrations/claude-agent.js.map +0 -1
  129. package/dist/otel/integrations/gemini.d.ts +0 -11
  130. package/dist/otel/integrations/gemini.d.ts.map +0 -1
  131. package/dist/otel/integrations/gemini.js +0 -23
  132. package/dist/otel/integrations/gemini.js.map +0 -1
  133. package/dist/otel/integrations/langchain.d.ts +0 -15
  134. package/dist/otel/integrations/langchain.d.ts.map +0 -1
  135. package/dist/otel/integrations/langchain.js +0 -43
  136. package/dist/otel/integrations/langchain.js.map +0 -1
  137. package/dist/otel/integrations/mastra.d.ts +0 -14
  138. package/dist/otel/integrations/mastra.d.ts.map +0 -1
  139. package/dist/otel/integrations/mastra.js +0 -31
  140. package/dist/otel/integrations/mastra.js.map +0 -1
  141. package/dist/otel/integrations/openai-agents.d.ts +0 -11
  142. package/dist/otel/integrations/openai-agents.d.ts.map +0 -1
  143. package/dist/otel/integrations/openai-agents.js +0 -30
  144. package/dist/otel/integrations/openai-agents.js.map +0 -1
  145. package/dist/otel/integrations/vercel.d.ts +0 -14
  146. package/dist/otel/integrations/vercel.d.ts.map +0 -1
  147. package/dist/otel/integrations/vercel.js +0 -20
  148. package/dist/otel/integrations/vercel.js.map +0 -1
  149. package/dist/otel/langchain-handler.d.ts +0 -112
  150. package/dist/otel/langchain-handler.d.ts.map +0 -1
  151. package/dist/otel/langchain-handler.js +0 -561
  152. package/dist/otel/langchain-handler.js.map +0 -1
  153. package/dist/otel/mastra-exporter.d.ts +0 -87
  154. package/dist/otel/mastra-exporter.d.ts.map +0 -1
  155. package/dist/otel/mastra-exporter.js +0 -530
  156. package/dist/otel/mastra-exporter.js.map +0 -1
  157. package/dist/otel/openai.d.ts +0 -20
  158. package/dist/otel/openai.d.ts.map +0 -1
  159. package/dist/otel/openai.js +0 -55
  160. package/dist/otel/openai.js.map +0 -1
  161. package/dist/otel/tracing-processor.d.ts +0 -139
  162. package/dist/otel/tracing-processor.d.ts.map +0 -1
  163. package/dist/otel/tracing-processor.js +0 -434
  164. package/dist/otel/tracing-processor.js.map +0 -1
  165. package/eslint.config.mjs +0 -4
  166. package/src/auth.ts +0 -236
  167. package/src/client.ts +0 -163
  168. package/src/converters/claude.ts +0 -343
  169. package/src/converters/gemini.ts +0 -243
  170. package/src/converters/index.ts +0 -50
  171. package/src/converters/openai.ts +0 -300
  172. package/src/converters/openinference.ts +0 -665
  173. package/src/converters/vercel.ts +0 -302
  174. package/src/dev-target.ts +0 -79
  175. package/src/http.ts +0 -43
  176. package/src/index.ts +0 -277
  177. package/src/otel/anthropic.ts +0 -619
  178. package/src/otel/claude-hooks.ts +0 -1116
  179. package/src/otel/claude-wrapper.ts +0 -239
  180. package/src/otel/gemini.ts +0 -483
  181. package/src/otel/index.ts +0 -128
  182. package/src/otel/init.ts +0 -411
  183. package/src/otel/integrations/anthropic.ts +0 -36
  184. package/src/otel/integrations/base.ts +0 -158
  185. package/src/otel/integrations/claude-agent.ts +0 -36
  186. package/src/otel/integrations/gemini.ts +0 -30
  187. package/src/otel/integrations/index.ts +0 -152
  188. package/src/otel/integrations/langchain.ts +0 -60
  189. package/src/otel/integrations/mastra.ts +0 -48
  190. package/src/otel/integrations/openai-agents.ts +0 -47
  191. package/src/otel/integrations/pi.ts +0 -28
  192. package/src/otel/integrations/vercel.ts +0 -26
  193. package/src/otel/langchain-handler.ts +0 -804
  194. package/src/otel/logs.ts +0 -395
  195. package/src/otel/mastra-exporter.ts +0 -714
  196. package/src/otel/openai.ts +0 -93
  197. package/src/otel/pi.ts +0 -94
  198. package/src/otel/register.ts +0 -50
  199. package/src/otel/setup.ts +0 -215
  200. package/src/otel/span-processor.ts +0 -512
  201. package/src/otel/tracing-processor.ts +0 -637
  202. package/src/pagination.ts +0 -10
  203. package/src/proxy-from-env.d.ts +0 -7
  204. package/src/resources/experiments.ts +0 -176
  205. package/src/resources/recipes.ts +0 -74
  206. package/src/resources/runtimes.ts +0 -31
  207. package/src/runner.ts +0 -213
  208. package/src/types.ts +0 -13
  209. package/src/utils.ts +0 -95
  210. package/src/version.ts +0 -2
  211. package/tsconfig.json +0 -8
@@ -1,665 +0,0 @@
1
- import type { Attributes } from "@opentelemetry/api";
2
- import type { ReadableSpan, SpanExporter } from "@opentelemetry/sdk-trace-base";
3
- import type {
4
- GenAiAttributes,
5
- InputMessage,
6
- OutputMessage,
7
- ReasoningPart,
8
- SystemInstruction,
9
- ToolDefinition,
10
- } from "@introspection-sdk/types";
11
- import { toAttributes } from "@introspection-sdk/types";
12
-
13
- const OI = {
14
- MODEL_NAME: "llm.model_name",
15
- SYSTEM: "llm.system",
16
- INVOCATION_PARAMETERS: "llm.invocation_parameters",
17
- TOKEN_COUNT_PROMPT: "llm.token_count.prompt",
18
- TOKEN_COUNT_COMPLETION: "llm.token_count.completion",
19
- TOKEN_COUNT_TOTAL: "llm.token_count.total",
20
-
21
- INPUT_MESSAGES: "llm.input_messages",
22
- OUTPUT_MESSAGES: "llm.output_messages",
23
-
24
- TOOLS: "llm.tools",
25
- TOOL_NAME: "tool.name",
26
- TOOL_DESCRIPTION: "tool.description",
27
- TOOL_PARAMETERS: "tool.parameters",
28
- TOOL_JSON_SCHEMA: "tool.json_schema",
29
-
30
- OUTPUT_VALUE: "output.value",
31
- OUTPUT_MIME_TYPE: "output.mime_type",
32
- } as const;
33
-
34
- /**
35
- * Check whether an OTel scope name belongs to an OpenInference instrumentor.
36
- *
37
- * @param scopeName - The `instrumentationScope.name` from a {@link ReadableSpan}.
38
- * @returns `true` when the scope starts with `"openinference"` or `"@arizeai/openinference"`.
39
- *
40
- * @example
41
- * ```ts
42
- * if (isOpenInferenceSpan(span.instrumentationScope.name)) {
43
- * // convert attributes …
44
- * }
45
- * ```
46
- */
47
- export function isOpenInferenceSpan(scopeName?: string): boolean {
48
- if (!scopeName) return false;
49
- return (
50
- scopeName.startsWith("openinference") ||
51
- scopeName.startsWith("@arizeai/openinference")
52
- );
53
- }
54
-
55
- function extractModel(attrs: Attributes): string | undefined {
56
- return attrs[OI.MODEL_NAME] as string | undefined;
57
- }
58
-
59
- function extractSystem(attrs: Attributes): string | undefined {
60
- return attrs[OI.SYSTEM] as string | undefined;
61
- }
62
-
63
- function extractTokenCounts(attrs: Attributes): {
64
- input?: number;
65
- output?: number;
66
- cacheCreation?: number;
67
- cacheRead?: number;
68
- } {
69
- return {
70
- input: attrs[OI.TOKEN_COUNT_PROMPT] as number | undefined,
71
- output: attrs[OI.TOKEN_COUNT_COMPLETION] as number | undefined,
72
- cacheCreation: attrs["llm.token_count.prompt_details.cache_write"] as
73
- number | undefined,
74
- cacheRead: attrs["llm.token_count.prompt_details.cache_read"] as
75
- number | undefined,
76
- };
77
- }
78
-
79
- type JsonObject = Record<string, unknown>;
80
-
81
- /** Safely traverse nested object path */
82
- function getPath(obj: unknown, ...keys: string[]): unknown {
83
- let current: unknown = obj;
84
- for (const key of keys) {
85
- if (typeof current !== "object" || current === null) return undefined;
86
- current = (current as JsonObject)[key];
87
- }
88
- return current;
89
- }
90
-
91
- /**
92
- * Extract response ID from LangChain's nested output structure.
93
- * Path: generations[*][*].message.kwargs.id
94
- */
95
- function extractLangChainResponseId(payload: unknown): string | undefined {
96
- const generations = getPath(payload, "generations");
97
- if (!Array.isArray(generations)) return undefined;
98
-
99
- for (const outer of generations) {
100
- const items = Array.isArray(outer) ? outer : [outer];
101
- for (const item of items) {
102
- const id = getPath(item, "message", "kwargs", "id");
103
- if (typeof id === "string" && id) return id;
104
- }
105
- }
106
- return undefined;
107
- }
108
-
109
- function extractResponseId(attrs: Attributes): string | undefined {
110
- const existing = attrs["gen_ai.response.id"];
111
- if (typeof existing === "string" && existing) return existing;
112
-
113
- const outputValue = attrs[OI.OUTPUT_VALUE];
114
- if (typeof outputValue !== "string") return undefined;
115
-
116
- try {
117
- const parsed = JSON.parse(outputValue);
118
- return parsed?.id ?? extractLangChainResponseId(parsed);
119
- } catch {
120
- return undefined;
121
- }
122
- }
123
-
124
- function extractSystemInstructions(
125
- attrs: Attributes,
126
- ): SystemInstruction[] | undefined {
127
- const inputValue = attrs["input.value"] as string | undefined;
128
- if (!inputValue) return undefined;
129
-
130
- try {
131
- const parsed = JSON.parse(inputValue);
132
- if (!parsed?.system) return undefined;
133
-
134
- // Plain string system prompt
135
- if (typeof parsed.system === "string") {
136
- return [{ type: "text", content: parsed.system }];
137
- }
138
-
139
- // Array of content blocks (e.g. Anthropic API with cache_control)
140
- if (Array.isArray(parsed.system)) {
141
- const instructions: SystemInstruction[] = [];
142
- for (const block of parsed.system) {
143
- if (block?.type === "text" && typeof block.text === "string") {
144
- instructions.push({ type: "text", content: block.text });
145
- }
146
- }
147
- return instructions.length > 0 ? instructions : undefined;
148
- }
149
- } catch {
150
- // ignore parse errors
151
- }
152
- return undefined;
153
- }
154
-
155
- function extractToolDefinitions(
156
- attrs: Attributes,
157
- ): ToolDefinition[] | undefined {
158
- const tools: ToolDefinition[] = [];
159
-
160
- for (const [key, value] of Object.entries(attrs)) {
161
- const match = key.match(/^llm\.tools\.(\d+)\.tool\.json_schema$/);
162
- if (!match || !value) continue;
163
-
164
- try {
165
- const raw = typeof value === "string" ? JSON.parse(value) : value;
166
-
167
- // LangChain format: {"type":"function","function":{name, description, parameters}}
168
- // Standard format: {title/name, description, parameters}
169
- const schema =
170
- raw?.type === "function" && raw?.function ? raw.function : raw;
171
-
172
- tools.push({
173
- type: "function",
174
- name: schema?.name ?? schema?.title ?? `tool_${match[1]}`,
175
- description: schema?.description,
176
- parameters: schema?.parameters ?? schema,
177
- });
178
- } catch {
179
- // Skip malformed JSON
180
- }
181
- }
182
-
183
- return tools.length > 0 ? tools : undefined;
184
- }
185
-
186
- function extractInputMessages(attrs: Attributes): InputMessage[] | undefined {
187
- const messages: InputMessage[] = [];
188
-
189
- const indices = new Set<number>();
190
- for (const key of Object.keys(attrs)) {
191
- const match = key.match(/^llm\.input_messages\.(\d+)\./);
192
- if (match && match[1]) {
193
- indices.add(parseInt(match[1], 10));
194
- }
195
- }
196
-
197
- for (const idx of Array.from(indices).sort((a, b) => a - b)) {
198
- const role = attrs[`llm.input_messages.${idx}.message.role`] as string;
199
- const content = attrs[
200
- `llm.input_messages.${idx}.message.content`
201
- ] as string;
202
-
203
- if (role) {
204
- const parts: InputMessage["parts"] = [];
205
- if (content) {
206
- parts.push({ type: "text", content });
207
- } else {
208
- // Structured content (e.g. Vercel AI SDK): llm.input_messages.{i}.message.contents.{j}.message_content.text
209
- const contentIndices = new Set<number>();
210
- for (const key of Object.keys(attrs)) {
211
- const m = key.match(
212
- new RegExp(
213
- `^llm\\.input_messages\\.${idx}\\.message\\.contents\\.(\\d+)\\.`,
214
- ),
215
- );
216
- if (m && m[1]) contentIndices.add(parseInt(m[1], 10));
217
- }
218
- for (const cIdx of Array.from(contentIndices).sort((a, b) => a - b)) {
219
- const prefix = `llm.input_messages.${idx}.message.contents.${cIdx}`;
220
- const type = attrs[`${prefix}.message_content.type`] as string;
221
- const text = attrs[`${prefix}.message_content.text`] as string;
222
- if (text) {
223
- parts.push({
224
- type: type === "text" ? "text" : "text",
225
- content: text,
226
- });
227
- }
228
- }
229
- }
230
- messages.push({ role: role as InputMessage["role"], parts });
231
- }
232
- }
233
-
234
- // Drop trailing assistant messages — these are prefills (e.g. `{`) injected
235
- // by the app to coerce JSON output, not real conversation turns.
236
- while (
237
- messages.length > 0 &&
238
- messages[messages.length - 1]!.role === "assistant"
239
- ) {
240
- messages.pop();
241
- }
242
-
243
- return messages.length > 0 ? messages : undefined;
244
- }
245
-
246
- function extractOutputMessages(attrs: Attributes): OutputMessage[] | undefined {
247
- const messages: OutputMessage[] = [];
248
-
249
- const indices = new Set<number>();
250
- for (const key of Object.keys(attrs)) {
251
- const match = key.match(/^llm\.output_messages\.(\d+)\./);
252
- if (match && match[1]) {
253
- indices.add(parseInt(match[1], 10));
254
- }
255
- }
256
-
257
- for (const idx of Array.from(indices).sort((a, b) => a - b)) {
258
- const role = attrs[`llm.output_messages.${idx}.message.role`] as string;
259
- const content = attrs[
260
- `llm.output_messages.${idx}.message.content`
261
- ] as string;
262
-
263
- if (role) {
264
- const parts: OutputMessage["parts"] = [];
265
- if (content) {
266
- parts.push({ type: "text", content });
267
- } else {
268
- // Structured content (e.g. Anthropic OI instrumentor): llm.output_messages.{i}.message.contents.{j}.message_content.text
269
- const contentIndices = new Set<number>();
270
- for (const key of Object.keys(attrs)) {
271
- const m = key.match(
272
- new RegExp(
273
- `^llm\\.output_messages\\.${idx}\\.message\\.contents\\.(\\d+)\\.`,
274
- ),
275
- );
276
- if (m && m[1]) contentIndices.add(parseInt(m[1], 10));
277
- }
278
- for (const cIdx of Array.from(contentIndices).sort((a, b) => a - b)) {
279
- const prefix = `llm.output_messages.${idx}.message.contents.${cIdx}`;
280
- const rawText =
281
- (attrs[`${prefix}.message_content.text`] as string | undefined) ??
282
- (attrs[`${prefix}.message.content.text`] as string | undefined);
283
- if (rawText) {
284
- parts.push({ type: "text", content: rawText });
285
- }
286
- }
287
- }
288
-
289
- const toolCallIndices = new Set<number>();
290
- for (const key of Object.keys(attrs)) {
291
- const match = key.match(
292
- new RegExp(
293
- `^llm\\.output_messages\\.${idx}\\.message\\.tool_calls\\.(\\d+)\\.`,
294
- ),
295
- );
296
- if (match && match[1]) {
297
- toolCallIndices.add(parseInt(match[1], 10));
298
- }
299
- }
300
-
301
- for (const tcIdx of Array.from(toolCallIndices).sort((a, b) => a - b)) {
302
- const prefix = `llm.output_messages.${idx}.message.tool_calls.${tcIdx}.tool_call`;
303
- const toolName = attrs[`${prefix}.function.name`] as string;
304
- const toolArgs = attrs[`${prefix}.function.arguments`] as string;
305
- const toolId = attrs[`${prefix}.id`] as string;
306
-
307
- if (toolName === "submit_response" && toolArgs) {
308
- // Extract thinking and response from submit_response tool call
309
- try {
310
- const parsed = JSON.parse(toolArgs) as Record<string, unknown>;
311
- if (typeof parsed.thinking === "string" && parsed.thinking) {
312
- const reasoningPart: ReasoningPart = {
313
- type: "reasoning",
314
- content: parsed.thinking,
315
- };
316
- parts.push(reasoningPart);
317
- }
318
- if (typeof parsed.response === "string" && parsed.response) {
319
- parts.push({ type: "text", content: parsed.response });
320
- }
321
- } catch {
322
- // Fall back to raw tool_call if JSON parse fails
323
- parts.push({
324
- type: "tool_call",
325
- name: toolName,
326
- arguments: toolArgs,
327
- id: toolId,
328
- });
329
- }
330
- } else if (toolName) {
331
- parts.push({
332
- type: "tool_call",
333
- name: toolName,
334
- arguments: toolArgs,
335
- id: toolId,
336
- });
337
- }
338
- }
339
-
340
- messages.push({ role: role as OutputMessage["role"], parts });
341
- }
342
- }
343
-
344
- // Fallback: if no llm.output_messages.* found, construct from output.value
345
- if (messages.length === 0) {
346
- const outputValue = attrs[OI.OUTPUT_VALUE] as string | undefined;
347
- if (typeof outputValue === "string" && outputValue) {
348
- messages.push({
349
- role: "assistant",
350
- parts: [{ type: "text", content: outputValue }],
351
- });
352
- }
353
- }
354
-
355
- return messages.length > 0 ? messages : undefined;
356
- }
357
-
358
- /**
359
- * Convert OpenInference span attributes to camelCase {@link GenAiAttributes}.
360
- *
361
- * Extracts `llm.*`, `tool.*`, and `output.*` keys and maps them to the
362
- * corresponding Gen AI semantic convention fields.
363
- *
364
- * @param attrs - Raw OTel {@link Attributes} from an OpenInference span.
365
- * @returns A {@link GenAiAttributes} object with all recognised fields populated.
366
- *
367
- * @example
368
- * ```ts
369
- * const genAi = convertOpenInferenceToGenAI(span.attributes);
370
- * console.log(genAi.requestModel); // e.g. "gpt-4"
371
- * ```
372
- */
373
- export function convertOpenInferenceToGenAI(
374
- attrs?: Attributes,
375
- ): GenAiAttributes {
376
- if (!attrs) return {};
377
-
378
- const result: GenAiAttributes = {};
379
-
380
- const model = extractModel(attrs);
381
- if (model) result.requestModel = model;
382
-
383
- const providerName = extractSystem(attrs);
384
- if (providerName) result.providerName = providerName;
385
-
386
- const responseId = extractResponseId(attrs);
387
- if (responseId) result.responseId = responseId;
388
-
389
- const tokens = extractTokenCounts(attrs);
390
- if (tokens.input !== undefined) result.inputTokens = tokens.input;
391
- if (tokens.output !== undefined) result.outputTokens = tokens.output;
392
- if (tokens.cacheCreation !== undefined)
393
- result.cacheCreationInputTokens = tokens.cacheCreation;
394
- if (tokens.cacheRead !== undefined)
395
- result.cacheReadInputTokens = tokens.cacheRead;
396
-
397
- const sysInstr = extractSystemInstructions(attrs);
398
- if (sysInstr) result.systemInstructions = sysInstr;
399
-
400
- const toolDefs = extractToolDefinitions(attrs);
401
- if (toolDefs) result.toolDefinitions = toolDefs;
402
-
403
- const inputMsgs = extractInputMessages(attrs);
404
- if (inputMsgs) result.inputMessages = inputMsgs;
405
-
406
- const outputMsgs = extractOutputMessages(attrs);
407
- if (outputMsgs) result.outputMessages = outputMsgs;
408
-
409
- // Default operation name to "chat" for LLM spans so the frontend can display them
410
- const spanKind = attrs["openinference.span.kind"];
411
- if (spanKind === "LLM" && !attrs["gen_ai.operation.name"]) {
412
- result.operationName = "chat";
413
- }
414
-
415
- return result;
416
- }
417
-
418
- /**
419
- * Replace all OpenInference `llm.*` / `tool.*` / `output.*` attributes with
420
- * their `gen_ai.*` equivalents, preserving every other attribute unchanged.
421
- *
422
- * @param attrs - Raw OTel {@link Attributes} that may contain OpenInference keys.
423
- * @returns A new {@link Attributes} dictionary with OpenInference keys replaced.
424
- *
425
- * @example
426
- * ```ts
427
- * const converted = replaceOpenInferenceWithGenAI(span.attributes);
428
- * // converted["gen_ai.request.model"] is set; "llm.model_name" is removed
429
- * ```
430
- */
431
- export function replaceOpenInferenceWithGenAI(attrs?: Attributes): Attributes {
432
- if (!attrs) return {};
433
-
434
- const genaiAttrs = convertOpenInferenceToGenAI(attrs);
435
- const result: Record<string, unknown> = {};
436
-
437
- for (const [key, value] of Object.entries(attrs)) {
438
- if (
439
- !key.startsWith("llm.") &&
440
- !key.startsWith("tool.") &&
441
- !key.startsWith("output.")
442
- ) {
443
- result[key] = value;
444
- }
445
- }
446
-
447
- const genaiOtelAttrs = toAttributes(genaiAttrs);
448
- for (const [key, value] of Object.entries(genaiOtelAttrs)) {
449
- result[key] = value;
450
- }
451
-
452
- return result as Attributes;
453
- }
454
-
455
- // ---------------------------------------------------------------------------
456
- // GenAI → OpenInference (reverse direction)
457
- // ---------------------------------------------------------------------------
458
-
459
- function flattenGenAIMessages(
460
- attrs: Record<string, unknown>,
461
- srcKey: string,
462
- prefix: string,
463
- ) {
464
- const raw = attrs[srcKey];
465
- if (!raw || typeof raw !== "string") return;
466
- try {
467
- const messages = JSON.parse(raw);
468
- if (!Array.isArray(messages)) return;
469
- messages.forEach(
470
- (
471
- msg: {
472
- role?: string;
473
- parts?: Array<{
474
- type: string;
475
- content?: string;
476
- name?: string;
477
- arguments?: string;
478
- id?: string;
479
- }>;
480
- content?: string;
481
- },
482
- i: number,
483
- ) => {
484
- if (msg.role) {
485
- attrs[`${prefix}.${i}.message.role`] = msg.role;
486
- }
487
- if (Array.isArray(msg.parts)) {
488
- const textParts = msg.parts.filter((p) => p.type === "text");
489
- if (textParts.length > 0) {
490
- attrs[`${prefix}.${i}.message.content`] = textParts
491
- .map((p) => p.content)
492
- .join("\n");
493
- }
494
- const toolCalls = msg.parts.filter((p) => p.type === "tool_call");
495
- toolCalls.forEach((tc, j) => {
496
- attrs[
497
- `${prefix}.${i}.message.tool_calls.${j}.tool_call.function.name`
498
- ] = tc.name;
499
- attrs[
500
- `${prefix}.${i}.message.tool_calls.${j}.tool_call.function.arguments`
501
- ] =
502
- typeof tc.arguments === "string"
503
- ? tc.arguments
504
- : JSON.stringify(tc.arguments);
505
- if (tc.id) {
506
- attrs[`${prefix}.${i}.message.tool_calls.${j}.tool_call.id`] =
507
- tc.id;
508
- }
509
- });
510
- }
511
- if (typeof msg.content === "string") {
512
- attrs[`${prefix}.${i}.message.content`] = msg.content;
513
- }
514
- },
515
- );
516
- } catch {
517
- // ignore parse errors
518
- }
519
- }
520
-
521
- /**
522
- * Enrich a {@link ReadableSpan} with OpenInference attributes derived from its
523
- * `gen_ai.*` attributes.
524
- *
525
- * Use this when exporting Mastra traces to Arize / Phoenix, which expects
526
- * OpenInference conventions (`openinference.span.kind`, `llm.model_name`,
527
- * flattened `llm.input_messages.N.message.role`, token counts, etc.).
528
- *
529
- * @param span - The OTel {@link ReadableSpan} to enrich.
530
- * @returns A shallow copy of the span with additional OpenInference attributes.
531
- *
532
- * @example
533
- * ```ts
534
- * const enriched = addOpenInferenceAttributes(span);
535
- * exporter.export([enriched], cb);
536
- * ```
537
- */
538
- export function addOpenInferenceAttributes(span: ReadableSpan): ReadableSpan {
539
- const attrs: Record<string, unknown> = { ...span.attributes };
540
- const spanType = attrs["mastra.span.type"] as string;
541
-
542
- switch (spanType) {
543
- case "MODEL_GENERATION":
544
- attrs["openinference.span.kind"] = "LLM";
545
- break;
546
- case "AGENT_RUN":
547
- attrs["openinference.span.kind"] = "CHAIN";
548
- break;
549
- case "TOOL_CALL":
550
- case "MCP_TOOL_CALL":
551
- attrs["openinference.span.kind"] = "TOOL";
552
- break;
553
- }
554
-
555
- if (attrs["gen_ai.request.model"]) {
556
- attrs[OI.MODEL_NAME] = attrs["gen_ai.request.model"];
557
- }
558
- if (attrs["gen_ai.provider.name"]) {
559
- attrs["llm.provider"] = attrs["gen_ai.provider.name"];
560
- }
561
-
562
- const inputTokens = attrs["gen_ai.usage.input_tokens"] as number | undefined;
563
- const outputTokens = attrs["gen_ai.usage.output_tokens"] as
564
- number | undefined;
565
- if (inputTokens !== undefined) {
566
- attrs[OI.TOKEN_COUNT_PROMPT] = inputTokens;
567
- }
568
- if (outputTokens !== undefined) {
569
- attrs[OI.TOKEN_COUNT_COMPLETION] = outputTokens;
570
- }
571
- if (inputTokens !== undefined && outputTokens !== undefined) {
572
- attrs[OI.TOKEN_COUNT_TOTAL] = inputTokens + outputTokens;
573
- }
574
-
575
- const params: Record<string, unknown> = {};
576
- if (attrs["gen_ai.request.temperature"] !== undefined)
577
- params.temperature = attrs["gen_ai.request.temperature"];
578
- if (attrs["gen_ai.request.max_tokens"] !== undefined)
579
- params.max_tokens = attrs["gen_ai.request.max_tokens"];
580
- if (attrs["gen_ai.request.top_p"] !== undefined)
581
- params.top_p = attrs["gen_ai.request.top_p"];
582
- if (Object.keys(params).length > 0) {
583
- attrs[OI.INVOCATION_PARAMETERS] = JSON.stringify(params);
584
- }
585
-
586
- flattenGenAIMessages(attrs, "gen_ai.input.messages", OI.INPUT_MESSAGES);
587
- flattenGenAIMessages(attrs, "gen_ai.output.messages", OI.OUTPUT_MESSAGES);
588
-
589
- if (attrs["mastra.agent_run.input"]) {
590
- attrs["input.value"] = attrs["mastra.agent_run.input"];
591
- }
592
- if (attrs["mastra.agent_run.output"]) {
593
- attrs[OI.OUTPUT_VALUE] = attrs["mastra.agent_run.output"];
594
- }
595
-
596
- if (attrs["gen_ai.tool.name"]) {
597
- attrs[OI.TOOL_NAME] = attrs["gen_ai.tool.name"];
598
- }
599
- if (attrs["gen_ai.tool.description"]) {
600
- attrs[OI.TOOL_DESCRIPTION] = attrs["gen_ai.tool.description"];
601
- }
602
- if (attrs["gen_ai.tool.call.arguments"]) {
603
- attrs["input.value"] = attrs["gen_ai.tool.call.arguments"];
604
- }
605
- if (attrs["gen_ai.tool.call.result"]) {
606
- attrs[OI.OUTPUT_VALUE] = attrs["gen_ai.tool.call.result"];
607
- }
608
-
609
- return {
610
- ...span,
611
- attributes: attrs as Attributes,
612
- spanContext: span.spanContext,
613
- };
614
- }
615
-
616
- /**
617
- * {@link SpanExporter} wrapper that enriches every span with OpenInference
618
- * attributes before forwarding it to the inner exporter.
619
- *
620
- * Use this when exporting Mastra / `gen_ai` traces to Arize or Phoenix.
621
- *
622
- * @example
623
- * ```ts
624
- * const otlp = new OTLPTraceExporter({ url: "https://otlp.arize.com/v1/traces" });
625
- * const exporter = new OpenInferenceSpanExporter(otlp);
626
- * provider.addSpanProcessor(new BatchSpanProcessor(exporter));
627
- * ```
628
- */
629
- export class OpenInferenceSpanExporter implements SpanExporter {
630
- /**
631
- * @param inner - The downstream {@link SpanExporter} to forward enriched spans to.
632
- */
633
- constructor(private inner: SpanExporter) {}
634
-
635
- /**
636
- * Enrich each span with OpenInference attributes, then forward the batch.
637
- *
638
- * @param spans - Completed spans to export.
639
- * @param resultCallback - Callback invoked with the export result code.
640
- */
641
- export(
642
- spans: ReadableSpan[],
643
- resultCallback: (result: { code: number }) => void,
644
- ): void {
645
- this.inner.export(spans.map(addOpenInferenceAttributes), resultCallback);
646
- }
647
-
648
- /**
649
- * Shut down the inner exporter.
650
- *
651
- * @returns A promise that resolves when the inner exporter has shut down.
652
- */
653
- async shutdown(): Promise<void> {
654
- return this.inner.shutdown();
655
- }
656
-
657
- /**
658
- * Flush any buffered spans in the inner exporter.
659
- *
660
- * @returns A promise that resolves when the flush completes.
661
- */
662
- async forceFlush(): Promise<void> {
663
- return this.inner.forceFlush?.();
664
- }
665
- }