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