@mastra/braintrust 1.0.0-beta.11 → 1.0.0-beta.13
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.
- package/CHANGELOG.md +70 -0
- package/README.md +47 -5
- package/dist/formatter.d.ts +99 -0
- package/dist/formatter.d.ts.map +1 -0
- package/dist/index.cjs +376 -343
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +377 -344
- package/dist/index.js.map +1 -1
- package/dist/thread-reconstruction.d.ts +47 -0
- package/dist/thread-reconstruction.d.ts.map +1 -0
- package/dist/tracing.d.ts +63 -48
- package/dist/tracing.d.ts.map +1 -1
- package/package.json +5 -4
package/dist/index.js
CHANGED
|
@@ -1,10 +1,140 @@
|
|
|
1
1
|
import { SpanType } from '@mastra/core/observability';
|
|
2
2
|
import { omitKeys } from '@mastra/core/utils';
|
|
3
|
-
import {
|
|
3
|
+
import { TrackingExporter } from '@mastra/observability';
|
|
4
4
|
import { initLogger, currentSpan } from 'braintrust';
|
|
5
5
|
|
|
6
6
|
// src/tracing.ts
|
|
7
7
|
|
|
8
|
+
// src/formatter.ts
|
|
9
|
+
function removeNullish(obj) {
|
|
10
|
+
return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
|
|
11
|
+
}
|
|
12
|
+
function convertContentPart(part) {
|
|
13
|
+
if (!part || typeof part !== "object") {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
switch (part.type) {
|
|
17
|
+
case "text":
|
|
18
|
+
return part.text || null;
|
|
19
|
+
case "image":
|
|
20
|
+
return "[image]";
|
|
21
|
+
case "file": {
|
|
22
|
+
const filePart = part;
|
|
23
|
+
if (filePart.filename || filePart.name) {
|
|
24
|
+
return `[file: ${filePart.filename || filePart.name}]`;
|
|
25
|
+
}
|
|
26
|
+
return "[file]";
|
|
27
|
+
}
|
|
28
|
+
case "reasoning": {
|
|
29
|
+
const reasoningPart = part;
|
|
30
|
+
if (typeof reasoningPart.text === "string" && reasoningPart.text.length > 0) {
|
|
31
|
+
return `[reasoning: ${reasoningPart.text.substring(0, 100)}${reasoningPart.text.length > 100 ? "..." : ""}]`;
|
|
32
|
+
}
|
|
33
|
+
return "[reasoning]";
|
|
34
|
+
}
|
|
35
|
+
case "tool-call":
|
|
36
|
+
return null;
|
|
37
|
+
case "tool-result":
|
|
38
|
+
return null;
|
|
39
|
+
default: {
|
|
40
|
+
const unknownPart = part;
|
|
41
|
+
if (typeof unknownPart.text === "string") {
|
|
42
|
+
return unknownPart.text;
|
|
43
|
+
}
|
|
44
|
+
if (typeof unknownPart.content === "string") {
|
|
45
|
+
return unknownPart.content;
|
|
46
|
+
}
|
|
47
|
+
return `[${unknownPart.type || "unknown"}]`;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function serializeToolResult(resultData) {
|
|
52
|
+
if (typeof resultData === "string") {
|
|
53
|
+
return resultData;
|
|
54
|
+
}
|
|
55
|
+
if (resultData && typeof resultData === "object" && "value" in resultData) {
|
|
56
|
+
const valueData = resultData.value;
|
|
57
|
+
return typeof valueData === "string" ? valueData : JSON.stringify(valueData);
|
|
58
|
+
}
|
|
59
|
+
if (resultData === void 0 || resultData === null) {
|
|
60
|
+
return "";
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
return JSON.stringify(resultData);
|
|
64
|
+
} catch {
|
|
65
|
+
return "[unserializable result]";
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function convertAISDKMessage(message) {
|
|
69
|
+
if (!message || typeof message !== "object") {
|
|
70
|
+
return message;
|
|
71
|
+
}
|
|
72
|
+
const { role, content, ...rest } = message;
|
|
73
|
+
if (typeof content === "string") {
|
|
74
|
+
return message;
|
|
75
|
+
}
|
|
76
|
+
if (Array.isArray(content)) {
|
|
77
|
+
if (content.length === 0) {
|
|
78
|
+
return { role, content: "", ...rest };
|
|
79
|
+
}
|
|
80
|
+
if (role === "user" || role === "system") {
|
|
81
|
+
const contentParts = content.map((part) => convertContentPart(part)).filter(Boolean);
|
|
82
|
+
return {
|
|
83
|
+
role,
|
|
84
|
+
content: contentParts.length > 0 ? contentParts.join("\n") : "",
|
|
85
|
+
...rest
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
if (role === "assistant") {
|
|
89
|
+
const contentParts = content.filter((part) => part?.type !== "tool-call").map((part) => convertContentPart(part)).filter(Boolean);
|
|
90
|
+
const toolCallParts = content.filter((part) => part?.type === "tool-call");
|
|
91
|
+
const result = {
|
|
92
|
+
role,
|
|
93
|
+
content: contentParts.length > 0 ? contentParts.join("\n") : "",
|
|
94
|
+
...rest
|
|
95
|
+
};
|
|
96
|
+
if (toolCallParts.length > 0) {
|
|
97
|
+
result.tool_calls = toolCallParts.map((tc) => {
|
|
98
|
+
const toolCall = tc;
|
|
99
|
+
const toolCallId = toolCall.toolCallId;
|
|
100
|
+
const toolName = toolCall.toolName;
|
|
101
|
+
const args = toolCall.args ?? toolCall.input;
|
|
102
|
+
let argsString;
|
|
103
|
+
if (typeof args === "string") {
|
|
104
|
+
argsString = args;
|
|
105
|
+
} else if (args !== void 0 && args !== null) {
|
|
106
|
+
argsString = JSON.stringify(args);
|
|
107
|
+
} else {
|
|
108
|
+
argsString = "{}";
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
id: toolCallId,
|
|
112
|
+
type: "function",
|
|
113
|
+
function: {
|
|
114
|
+
name: toolName,
|
|
115
|
+
arguments: argsString
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
if (role === "tool") {
|
|
123
|
+
const toolResult = content.find((part) => part?.type === "tool-result");
|
|
124
|
+
if (toolResult) {
|
|
125
|
+
const resultData = toolResult.output ?? toolResult.result;
|
|
126
|
+
const resultContent = serializeToolResult(resultData);
|
|
127
|
+
return {
|
|
128
|
+
role: "tool",
|
|
129
|
+
content: resultContent,
|
|
130
|
+
tool_call_id: toolResult.toolCallId
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return message;
|
|
136
|
+
}
|
|
137
|
+
|
|
8
138
|
// src/metrics.ts
|
|
9
139
|
function formatUsageMetrics(usage) {
|
|
10
140
|
const metrics = {};
|
|
@@ -29,8 +159,61 @@ function formatUsageMetrics(usage) {
|
|
|
29
159
|
return metrics;
|
|
30
160
|
}
|
|
31
161
|
|
|
162
|
+
// src/thread-reconstruction.ts
|
|
163
|
+
function reconstructThreadOutput(threadData, originalOutput) {
|
|
164
|
+
const messages = [];
|
|
165
|
+
const sortedSteps = [...threadData].sort((a, b) => a.stepIndex - b.stepIndex);
|
|
166
|
+
for (const step of sortedSteps) {
|
|
167
|
+
const sortedToolCalls = step.toolCalls ? [...step.toolCalls].sort((a, b) => {
|
|
168
|
+
if (!a.startTime || !b.startTime) return 0;
|
|
169
|
+
return a.startTime.getTime() - b.startTime.getTime();
|
|
170
|
+
}) : [];
|
|
171
|
+
if (sortedToolCalls.length > 0) {
|
|
172
|
+
messages.push({
|
|
173
|
+
role: "assistant",
|
|
174
|
+
content: step.text || "",
|
|
175
|
+
tool_calls: sortedToolCalls.map((tc) => {
|
|
176
|
+
const cleanArgs = tc.args && typeof tc.args === "object" && !Array.isArray(tc.args) ? removeNullish(tc.args) : tc.args;
|
|
177
|
+
return {
|
|
178
|
+
id: tc.toolCallId,
|
|
179
|
+
type: "function",
|
|
180
|
+
function: {
|
|
181
|
+
name: tc.toolName,
|
|
182
|
+
arguments: typeof cleanArgs === "string" ? cleanArgs : JSON.stringify(cleanArgs)
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
})
|
|
186
|
+
});
|
|
187
|
+
for (const tc of sortedToolCalls) {
|
|
188
|
+
if (tc.result !== void 0) {
|
|
189
|
+
messages.push({
|
|
190
|
+
role: "tool",
|
|
191
|
+
content: typeof tc.result === "string" ? tc.result : JSON.stringify(tc.result),
|
|
192
|
+
tool_call_id: tc.toolCallId
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
} else if (step.text) {
|
|
197
|
+
messages.push({
|
|
198
|
+
role: "assistant",
|
|
199
|
+
content: step.text
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (messages.length > 0) {
|
|
204
|
+
const lastMessage = messages[messages.length - 1];
|
|
205
|
+
const originalText = originalOutput?.text;
|
|
206
|
+
if (originalText && lastMessage.role === "tool") {
|
|
207
|
+
messages.push({
|
|
208
|
+
role: "assistant",
|
|
209
|
+
content: originalText
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return messages;
|
|
214
|
+
}
|
|
215
|
+
|
|
32
216
|
// src/tracing.ts
|
|
33
|
-
var MASTRA_TRACE_ID_METADATA_KEY = "mastra-trace-id";
|
|
34
217
|
var DEFAULT_SPAN_TYPE = "task";
|
|
35
218
|
var SPAN_TYPE_EXCEPTIONS = {
|
|
36
219
|
[SpanType.MODEL_GENERATION]: "llm",
|
|
@@ -42,383 +225,235 @@ var SPAN_TYPE_EXCEPTIONS = {
|
|
|
42
225
|
function mapSpanType(spanType) {
|
|
43
226
|
return SPAN_TYPE_EXCEPTIONS[spanType] ?? DEFAULT_SPAN_TYPE;
|
|
44
227
|
}
|
|
45
|
-
var BraintrustExporter = class extends
|
|
228
|
+
var BraintrustExporter = class extends TrackingExporter {
|
|
46
229
|
name = "braintrust";
|
|
47
|
-
traceMap = /* @__PURE__ */ new Map();
|
|
48
|
-
config;
|
|
49
230
|
// Flags and logger for context-aware mode
|
|
50
|
-
useProvidedLogger;
|
|
51
|
-
providedLogger;
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
231
|
+
#useProvidedLogger;
|
|
232
|
+
#providedLogger;
|
|
233
|
+
#localLogger;
|
|
234
|
+
constructor(config = {}) {
|
|
235
|
+
const resolvedApiKey = config.apiKey ?? process.env.BRAINTRUST_API_KEY;
|
|
236
|
+
const resolvedEndpoint = config.endpoint ?? process.env.BRAINTRUST_ENDPOINT;
|
|
237
|
+
super({
|
|
238
|
+
...config,
|
|
239
|
+
apiKey: resolvedApiKey,
|
|
240
|
+
endpoint: resolvedEndpoint
|
|
241
|
+
});
|
|
242
|
+
this.#useProvidedLogger = !!config.braintrustLogger;
|
|
243
|
+
if (this.#useProvidedLogger) {
|
|
244
|
+
this.#providedLogger = config.braintrustLogger;
|
|
58
245
|
} else {
|
|
59
|
-
if (!config.apiKey) {
|
|
60
|
-
this.setDisabled(
|
|
61
|
-
|
|
62
|
-
|
|
246
|
+
if (!this.config.apiKey) {
|
|
247
|
+
this.setDisabled(
|
|
248
|
+
`Missing required API key. Set BRAINTRUST_API_KEY environment variable or pass apiKey in config.`
|
|
249
|
+
);
|
|
63
250
|
return;
|
|
64
251
|
}
|
|
65
|
-
this
|
|
66
|
-
this.config = config;
|
|
252
|
+
this.#localLogger = void 0;
|
|
67
253
|
}
|
|
68
254
|
}
|
|
69
|
-
async
|
|
70
|
-
if (
|
|
71
|
-
|
|
72
|
-
return;
|
|
255
|
+
async getLocalLogger() {
|
|
256
|
+
if (this.#localLogger) {
|
|
257
|
+
return this.#localLogger;
|
|
73
258
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
259
|
+
try {
|
|
260
|
+
const logger = await initLogger({
|
|
261
|
+
projectName: this.config.projectName ?? "mastra-tracing",
|
|
262
|
+
apiKey: this.config.apiKey,
|
|
263
|
+
appUrl: this.config.endpoint,
|
|
264
|
+
...this.config.tuningParameters
|
|
265
|
+
});
|
|
266
|
+
this.#localLogger = logger;
|
|
267
|
+
return logger;
|
|
268
|
+
} catch (err) {
|
|
269
|
+
this.logger.error("Braintrust exporter: Failed to initialize logger", { error: err });
|
|
270
|
+
this.setDisabled("Failed to initialize Braintrust logger");
|
|
84
271
|
}
|
|
85
272
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (this.useProvidedLogger) {
|
|
89
|
-
await this.initLoggerOrUseContext(span);
|
|
90
|
-
} else {
|
|
91
|
-
await this.initLoggerPerTrace(span);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
const method = "handleSpanStarted";
|
|
95
|
-
const spanData = this.getSpanData({ span, method });
|
|
96
|
-
if (!spanData) {
|
|
97
|
-
return;
|
|
98
|
-
}
|
|
99
|
-
if (!span.isEvent) {
|
|
100
|
-
spanData.activeIds.add(span.id);
|
|
101
|
-
}
|
|
102
|
-
const braintrustParent = this.getBraintrustParent({ spanData, span, method });
|
|
103
|
-
if (!braintrustParent) {
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
273
|
+
startSpan(args) {
|
|
274
|
+
const { parent, span } = args;
|
|
106
275
|
const payload = this.buildSpanPayload(span);
|
|
107
|
-
const braintrustSpan =
|
|
276
|
+
const braintrustSpan = parent.startSpan({
|
|
108
277
|
spanId: span.id,
|
|
109
278
|
name: span.name,
|
|
110
279
|
type: mapSpanType(span.type),
|
|
280
|
+
startTime: span.startTime.getTime() / 1e3,
|
|
281
|
+
event: { id: span.id },
|
|
282
|
+
// Use Mastra span ID as Braintrust row ID for logFeedback() compatibility
|
|
111
283
|
...payload
|
|
112
284
|
});
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
285
|
+
const isModelGeneration = span.type === SpanType.MODEL_GENERATION;
|
|
286
|
+
return {
|
|
287
|
+
span: braintrustSpan,
|
|
288
|
+
spanType: span.type,
|
|
289
|
+
threadData: isModelGeneration ? [] : void 0,
|
|
290
|
+
pendingToolResults: isModelGeneration ? /* @__PURE__ */ new Map() : void 0
|
|
291
|
+
};
|
|
120
292
|
}
|
|
121
|
-
async
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
}
|
|
127
|
-
const braintrustSpan = spanData.spans.get(span.id);
|
|
128
|
-
if (!braintrustSpan) {
|
|
129
|
-
this.logger.warn("Braintrust exporter: No Braintrust span found for span update/end", {
|
|
130
|
-
traceId: span.traceId,
|
|
131
|
-
spanId: span.id,
|
|
132
|
-
spanName: span.name,
|
|
133
|
-
spanType: span.type,
|
|
134
|
-
isRootSpan: span.isRootSpan,
|
|
135
|
-
parentSpanId: span.parentSpanId,
|
|
136
|
-
method
|
|
137
|
-
});
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
140
|
-
braintrustSpan.log(this.buildSpanPayload(span));
|
|
141
|
-
if (isEnd) {
|
|
142
|
-
if (span.endTime) {
|
|
143
|
-
braintrustSpan.end({ endTime: span.endTime.getTime() / 1e3 });
|
|
293
|
+
async _buildRoot(_args) {
|
|
294
|
+
if (this.#useProvidedLogger) {
|
|
295
|
+
const externalSpan = currentSpan();
|
|
296
|
+
if (externalSpan && externalSpan.id) {
|
|
297
|
+
return externalSpan;
|
|
144
298
|
} else {
|
|
145
|
-
|
|
146
|
-
}
|
|
147
|
-
if (!span.isEvent) {
|
|
148
|
-
spanData.activeIds.delete(span.id);
|
|
149
|
-
}
|
|
150
|
-
if (spanData.activeIds.size === 0 && !spanData.isExternal) {
|
|
151
|
-
this.traceMap.delete(span.traceId);
|
|
299
|
+
return this.#providedLogger;
|
|
152
300
|
}
|
|
301
|
+
} else {
|
|
302
|
+
return this.getLocalLogger();
|
|
153
303
|
}
|
|
154
304
|
}
|
|
155
|
-
async
|
|
305
|
+
async _buildSpan(args) {
|
|
306
|
+
const { span, traceData } = args;
|
|
156
307
|
if (span.isRootSpan) {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
if (
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
await this.initLoggerPerTrace(span);
|
|
308
|
+
const root = traceData.getRoot();
|
|
309
|
+
if (root) {
|
|
310
|
+
return this.startSpan({ parent: root, span });
|
|
311
|
+
}
|
|
312
|
+
} else {
|
|
313
|
+
const parent = traceData.getParent(args);
|
|
314
|
+
if (parent) {
|
|
315
|
+
const parentSpan = "span" in parent ? parent.span : parent;
|
|
316
|
+
return this.startSpan({ parent: parentSpan, span });
|
|
167
317
|
}
|
|
168
318
|
}
|
|
169
|
-
|
|
170
|
-
|
|
319
|
+
}
|
|
320
|
+
async _buildEvent(args) {
|
|
321
|
+
const spanData = await this._buildSpan(args);
|
|
171
322
|
if (!spanData) {
|
|
172
323
|
return;
|
|
173
324
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
const payload = this.buildSpanPayload(span);
|
|
179
|
-
const braintrustSpan = braintrustParent.startSpan({
|
|
180
|
-
spanId: span.id,
|
|
181
|
-
name: span.name,
|
|
182
|
-
type: mapSpanType(span.type),
|
|
183
|
-
startTime: span.startTime.getTime() / 1e3,
|
|
184
|
-
...payload
|
|
185
|
-
});
|
|
186
|
-
braintrustSpan.end({ endTime: span.startTime.getTime() / 1e3 });
|
|
325
|
+
spanData.span.end({ endTime: args.span.startTime.getTime() / 1e3 });
|
|
326
|
+
return spanData.span;
|
|
187
327
|
}
|
|
188
|
-
|
|
189
|
-
const {
|
|
190
|
-
|
|
191
|
-
|
|
328
|
+
async _updateSpan(args) {
|
|
329
|
+
const { span, traceData } = args;
|
|
330
|
+
const spanData = traceData.getSpan({ spanId: span.id });
|
|
331
|
+
if (!spanData) {
|
|
192
332
|
return;
|
|
193
333
|
}
|
|
194
|
-
|
|
195
|
-
logger,
|
|
196
|
-
spans: /* @__PURE__ */ new Map(),
|
|
197
|
-
activeIds: /* @__PURE__ */ new Set(),
|
|
198
|
-
isExternal
|
|
199
|
-
});
|
|
334
|
+
spanData.span.log(this.buildSpanPayload(span, false));
|
|
200
335
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
if (this.traceMap.has(span.traceId)) {
|
|
206
|
-
this.logger.debug("Braintrust exporter: Reusing existing trace from local map", { traceId: span.traceId });
|
|
336
|
+
async _finishSpan(args) {
|
|
337
|
+
const { span, traceData } = args;
|
|
338
|
+
const spanData = traceData.getSpan({ spanId: span.id });
|
|
339
|
+
if (!spanData) {
|
|
207
340
|
return;
|
|
208
341
|
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
appUrl: this.config.endpoint,
|
|
214
|
-
...this.config.tuningParameters
|
|
215
|
-
});
|
|
216
|
-
this.initTraceMap({ logger: loggerInstance, isExternal: false, traceId: span.traceId });
|
|
217
|
-
} catch (err) {
|
|
218
|
-
this.logger.error("Braintrust exporter: Failed to initialize logger", { error: err, traceId: span.traceId });
|
|
219
|
-
this.setDisabled("Failed to initialize Braintrust logger");
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
/**
|
|
223
|
-
* Uses provided logger and detects external Braintrust spans.
|
|
224
|
-
* If a Braintrust span is detected (from logger.traced() or Eval()), attaches to it.
|
|
225
|
-
* Otherwise, uses the provided logger instance.
|
|
226
|
-
*/
|
|
227
|
-
async initLoggerOrUseContext(span) {
|
|
228
|
-
if (this.traceMap.has(span.traceId)) {
|
|
229
|
-
this.logger.debug("Braintrust exporter: Reusing existing trace from local map", { traceId: span.traceId });
|
|
230
|
-
return;
|
|
342
|
+
if (span.type === SpanType.MODEL_STEP) {
|
|
343
|
+
this.accumulateModelStepData(span, traceData);
|
|
344
|
+
} else if (span.type === SpanType.TOOL_CALL) {
|
|
345
|
+
this.accumulateToolCallResult(span, traceData);
|
|
231
346
|
}
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
|
|
347
|
+
const payload = span.type === SpanType.MODEL_GENERATION ? this.buildModelGenerationPayload(span, spanData) : this.buildSpanPayload(span, false);
|
|
348
|
+
spanData.span.log(payload);
|
|
349
|
+
if (span.endTime) {
|
|
350
|
+
spanData.span.end({ endTime: span.endTime.getTime() / 1e3 });
|
|
235
351
|
} else {
|
|
236
|
-
|
|
352
|
+
spanData.span.end();
|
|
237
353
|
}
|
|
238
354
|
}
|
|
239
|
-
|
|
240
|
-
const { span,
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
this.logger.warn("Braintrust exporter: No span data found for span", {
|
|
245
|
-
traceId: span.traceId,
|
|
246
|
-
spanId: span.id,
|
|
247
|
-
spanName: span.name,
|
|
248
|
-
spanType: span.type,
|
|
249
|
-
isRootSpan: span.isRootSpan,
|
|
250
|
-
parentSpanId: span.parentSpanId,
|
|
251
|
-
method
|
|
252
|
-
});
|
|
253
|
-
}
|
|
254
|
-
getBraintrustParent(options) {
|
|
255
|
-
const { spanData, span, method } = options;
|
|
256
|
-
const parentId = span.parentSpanId;
|
|
257
|
-
if (!parentId) {
|
|
258
|
-
return spanData.logger;
|
|
259
|
-
}
|
|
260
|
-
if (spanData.spans.has(parentId)) {
|
|
261
|
-
return spanData.spans.get(parentId);
|
|
262
|
-
}
|
|
263
|
-
if (parentId && !spanData.spans.has(parentId)) {
|
|
264
|
-
return spanData.logger;
|
|
265
|
-
}
|
|
266
|
-
this.logger.warn("Braintrust exporter: No parent data found for span", {
|
|
267
|
-
traceId: span.traceId,
|
|
268
|
-
spanId: span.id,
|
|
269
|
-
spanName: span.name,
|
|
270
|
-
spanType: span.type,
|
|
271
|
-
isRootSpan: span.isRootSpan,
|
|
272
|
-
parentSpanId: span.parentSpanId,
|
|
273
|
-
method
|
|
355
|
+
async _abortSpan(args) {
|
|
356
|
+
const { span: spanData, reason } = args;
|
|
357
|
+
spanData.span.log({
|
|
358
|
+
error: reason.message,
|
|
359
|
+
metadata: { errorDetails: reason }
|
|
274
360
|
});
|
|
361
|
+
spanData.span.end();
|
|
275
362
|
}
|
|
363
|
+
// ==============================================================================
|
|
364
|
+
// Thread view reconstruction helpers
|
|
365
|
+
// ==============================================================================
|
|
276
366
|
/**
|
|
277
|
-
*
|
|
278
|
-
*
|
|
279
|
-
* Supports both AI SDK v4 and v5 formats:
|
|
280
|
-
* - v4 uses 'args' for tool calls and 'result' for tool results
|
|
281
|
-
* - v5 uses 'input' for tool calls and 'output' for tool results
|
|
282
|
-
*
|
|
283
|
-
* AI SDK format:
|
|
284
|
-
* { role: "user", content: [{ type: "text", text: "hello" }] }
|
|
285
|
-
* { role: "assistant", content: [{ type: "text", text: "..." }, { type: "tool-call", toolCallId: "...", toolName: "...", args: {...} }] }
|
|
286
|
-
* { role: "tool", content: [{ type: "tool-result", toolCallId: "...", result: {...} }] }
|
|
287
|
-
*
|
|
288
|
-
* OpenAI format (what Braintrust expects):
|
|
289
|
-
* { role: "user", content: "hello" }
|
|
290
|
-
* { role: "assistant", content: "...", tool_calls: [{ id: "...", type: "function", function: { name: "...", arguments: "..." } }] }
|
|
291
|
-
* { role: "tool", content: "result", tool_call_id: "..." }
|
|
367
|
+
* Walk up the tree to find the MODEL_GENERATION ancestor span.
|
|
368
|
+
* Returns the BraintrustSpanData if found, undefined otherwise.
|
|
292
369
|
*/
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
if (Array.isArray(content)) {
|
|
302
|
-
if (content.length === 0) {
|
|
303
|
-
return { role, content: "", ...rest };
|
|
304
|
-
}
|
|
305
|
-
if (role === "user" || role === "system") {
|
|
306
|
-
const contentParts = content.map((part) => this.convertContentPart(part)).filter(Boolean);
|
|
307
|
-
return {
|
|
308
|
-
role,
|
|
309
|
-
content: contentParts.length > 0 ? contentParts.join("\n") : "",
|
|
310
|
-
...rest
|
|
311
|
-
};
|
|
312
|
-
}
|
|
313
|
-
if (role === "assistant") {
|
|
314
|
-
const contentParts = content.filter((part) => part?.type !== "tool-call").map((part) => this.convertContentPart(part)).filter(Boolean);
|
|
315
|
-
const toolCallParts = content.filter((part) => part?.type === "tool-call");
|
|
316
|
-
const result = {
|
|
317
|
-
role,
|
|
318
|
-
content: contentParts.length > 0 ? contentParts.join("\n") : "",
|
|
319
|
-
...rest
|
|
320
|
-
};
|
|
321
|
-
if (toolCallParts.length > 0) {
|
|
322
|
-
result.tool_calls = toolCallParts.map((tc) => {
|
|
323
|
-
const toolCallId = tc.toolCallId;
|
|
324
|
-
const toolName = tc.toolName;
|
|
325
|
-
const args = tc.args ?? tc.input;
|
|
326
|
-
let argsString;
|
|
327
|
-
if (typeof args === "string") {
|
|
328
|
-
argsString = args;
|
|
329
|
-
} else if (args !== void 0 && args !== null) {
|
|
330
|
-
argsString = JSON.stringify(args);
|
|
331
|
-
} else {
|
|
332
|
-
argsString = "{}";
|
|
333
|
-
}
|
|
334
|
-
return {
|
|
335
|
-
id: toolCallId,
|
|
336
|
-
type: "function",
|
|
337
|
-
function: {
|
|
338
|
-
name: toolName,
|
|
339
|
-
arguments: argsString
|
|
340
|
-
}
|
|
341
|
-
};
|
|
342
|
-
});
|
|
343
|
-
}
|
|
344
|
-
return result;
|
|
345
|
-
}
|
|
346
|
-
if (role === "tool") {
|
|
347
|
-
const toolResult = content.find((part) => part?.type === "tool-result");
|
|
348
|
-
if (toolResult) {
|
|
349
|
-
const resultData = toolResult.output ?? toolResult.result;
|
|
350
|
-
const resultContent = this.serializeToolResult(resultData);
|
|
351
|
-
return {
|
|
352
|
-
role: "tool",
|
|
353
|
-
content: resultContent,
|
|
354
|
-
tool_call_id: toolResult.toolCallId
|
|
355
|
-
};
|
|
356
|
-
}
|
|
370
|
+
findModelGenerationAncestor(spanId, traceData) {
|
|
371
|
+
let currentId = spanId;
|
|
372
|
+
while (currentId) {
|
|
373
|
+
const parentId = traceData.getParentId({ spanId: currentId });
|
|
374
|
+
if (!parentId) return void 0;
|
|
375
|
+
const parentSpanData = traceData.getSpan({ spanId: parentId });
|
|
376
|
+
if (parentSpanData?.spanType === SpanType.MODEL_GENERATION) {
|
|
377
|
+
return parentSpanData;
|
|
357
378
|
}
|
|
379
|
+
currentId = parentId;
|
|
358
380
|
}
|
|
359
|
-
return
|
|
381
|
+
return void 0;
|
|
360
382
|
}
|
|
361
383
|
/**
|
|
362
|
-
*
|
|
363
|
-
*
|
|
384
|
+
* Accumulate MODEL_STEP data to the parent MODEL_GENERATION's threadData.
|
|
385
|
+
* Called when a MODEL_STEP span ends.
|
|
364
386
|
*/
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
switch (part.type) {
|
|
370
|
-
case "text":
|
|
371
|
-
return part.text || null;
|
|
372
|
-
case "image":
|
|
373
|
-
return "[image]";
|
|
374
|
-
case "file": {
|
|
375
|
-
const filePart = part;
|
|
376
|
-
if (filePart.filename || filePart.name) {
|
|
377
|
-
return `[file: ${filePart.filename || filePart.name}]`;
|
|
378
|
-
}
|
|
379
|
-
return "[file]";
|
|
380
|
-
}
|
|
381
|
-
case "reasoning": {
|
|
382
|
-
const reasoningPart = part;
|
|
383
|
-
if (typeof reasoningPart.text === "string" && reasoningPart.text.length > 0) {
|
|
384
|
-
return `[reasoning: ${reasoningPart.text.substring(0, 100)}${reasoningPart.text.length > 100 ? "..." : ""}]`;
|
|
385
|
-
}
|
|
386
|
-
return "[reasoning]";
|
|
387
|
-
}
|
|
388
|
-
case "tool-call":
|
|
389
|
-
return null;
|
|
390
|
-
case "tool-result":
|
|
391
|
-
return null;
|
|
392
|
-
default: {
|
|
393
|
-
const unknownPart = part;
|
|
394
|
-
if (typeof unknownPart.text === "string") {
|
|
395
|
-
return unknownPart.text;
|
|
396
|
-
}
|
|
397
|
-
if (typeof unknownPart.content === "string") {
|
|
398
|
-
return unknownPart.content;
|
|
399
|
-
}
|
|
400
|
-
return `[${unknownPart.type || "unknown"}]`;
|
|
401
|
-
}
|
|
387
|
+
accumulateModelStepData(span, traceData) {
|
|
388
|
+
const modelGenSpanData = this.findModelGenerationAncestor(span.id, traceData);
|
|
389
|
+
if (!modelGenSpanData?.threadData) {
|
|
390
|
+
return;
|
|
402
391
|
}
|
|
392
|
+
const output = span.output;
|
|
393
|
+
const attributes = span.attributes;
|
|
394
|
+
const stepData = {
|
|
395
|
+
stepSpanId: span.id,
|
|
396
|
+
stepIndex: attributes?.stepIndex ?? 0,
|
|
397
|
+
text: output?.text,
|
|
398
|
+
toolCalls: output?.toolCalls?.map((tc) => ({
|
|
399
|
+
toolCallId: tc.toolCallId,
|
|
400
|
+
toolName: tc.toolName,
|
|
401
|
+
args: tc.args
|
|
402
|
+
}))
|
|
403
|
+
};
|
|
404
|
+
modelGenSpanData.threadData.push(stepData);
|
|
403
405
|
}
|
|
404
406
|
/**
|
|
405
|
-
*
|
|
407
|
+
* Store TOOL_CALL result in parent MODEL_GENERATION's pendingToolResults.
|
|
408
|
+
* Called when a TOOL_CALL span ends.
|
|
409
|
+
* Results are merged into threadData when MODEL_GENERATION ends.
|
|
406
410
|
*/
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
411
|
+
accumulateToolCallResult(span, traceData) {
|
|
412
|
+
const modelGenSpanData = this.findModelGenerationAncestor(span.id, traceData);
|
|
413
|
+
if (!modelGenSpanData?.pendingToolResults) {
|
|
414
|
+
return;
|
|
410
415
|
}
|
|
411
|
-
|
|
412
|
-
|
|
416
|
+
const input = span.input;
|
|
417
|
+
const toolCallId = input?.toolCallId;
|
|
418
|
+
if (!toolCallId) {
|
|
419
|
+
return;
|
|
413
420
|
}
|
|
414
|
-
|
|
415
|
-
|
|
421
|
+
modelGenSpanData.pendingToolResults.set(toolCallId, {
|
|
422
|
+
result: span.output,
|
|
423
|
+
startTime: span.startTime
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Build the payload for MODEL_GENERATION span, reconstructing output from threadData if available.
|
|
428
|
+
*/
|
|
429
|
+
buildModelGenerationPayload(span, spanData) {
|
|
430
|
+
const basePayload = this.buildSpanPayload(span, false);
|
|
431
|
+
const threadData = spanData.threadData;
|
|
432
|
+
if (!threadData || threadData.length === 0) {
|
|
433
|
+
return basePayload;
|
|
434
|
+
}
|
|
435
|
+
if (spanData.pendingToolResults && spanData.pendingToolResults.size > 0) {
|
|
436
|
+
for (const step of threadData) {
|
|
437
|
+
if (step.toolCalls) {
|
|
438
|
+
for (const toolCall of step.toolCalls) {
|
|
439
|
+
const pendingResult = spanData.pendingToolResults.get(toolCall.toolCallId);
|
|
440
|
+
if (pendingResult) {
|
|
441
|
+
toolCall.result = pendingResult.result;
|
|
442
|
+
toolCall.startTime = pendingResult.startTime;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
416
447
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
return "[unserializable result]";
|
|
448
|
+
const hasToolCalls = threadData.some((step) => step.toolCalls && step.toolCalls.length > 0);
|
|
449
|
+
if (!hasToolCalls) {
|
|
450
|
+
return basePayload;
|
|
421
451
|
}
|
|
452
|
+
const reconstructedOutput = reconstructThreadOutput(threadData, span.output);
|
|
453
|
+
return {
|
|
454
|
+
...basePayload,
|
|
455
|
+
output: reconstructedOutput
|
|
456
|
+
};
|
|
422
457
|
}
|
|
423
458
|
/**
|
|
424
459
|
* Transforms MODEL_GENERATION input to Braintrust Thread view format.
|
|
@@ -428,10 +463,10 @@ var BraintrustExporter = class extends BaseExporter {
|
|
|
428
463
|
transformInput(input, spanType) {
|
|
429
464
|
if (spanType === SpanType.MODEL_GENERATION) {
|
|
430
465
|
if (Array.isArray(input)) {
|
|
431
|
-
return input.map((msg) =>
|
|
466
|
+
return input.map((msg) => convertAISDKMessage(msg));
|
|
432
467
|
}
|
|
433
|
-
if (input && Array.isArray(input.messages)) {
|
|
434
|
-
return input.messages.map((msg) =>
|
|
468
|
+
if (input && typeof input === "object" && "messages" in input && Array.isArray(input.messages)) {
|
|
469
|
+
return input.messages.map((msg) => convertAISDKMessage(msg));
|
|
435
470
|
}
|
|
436
471
|
}
|
|
437
472
|
return input;
|
|
@@ -441,12 +476,15 @@ var BraintrustExporter = class extends BaseExporter {
|
|
|
441
476
|
*/
|
|
442
477
|
transformOutput(output, spanType) {
|
|
443
478
|
if (spanType === SpanType.MODEL_GENERATION) {
|
|
479
|
+
if (!output || typeof output !== "object") {
|
|
480
|
+
return output;
|
|
481
|
+
}
|
|
444
482
|
const { text, ...rest } = output;
|
|
445
|
-
return { role: "assistant", content: text, ...rest };
|
|
483
|
+
return { role: "assistant", content: text, ...removeNullish(rest) };
|
|
446
484
|
}
|
|
447
485
|
return output;
|
|
448
486
|
}
|
|
449
|
-
buildSpanPayload(span) {
|
|
487
|
+
buildSpanPayload(span, isCreate = true) {
|
|
450
488
|
const payload = {};
|
|
451
489
|
if (span.input !== void 0) {
|
|
452
490
|
payload.input = this.transformInput(span.input, span.type);
|
|
@@ -454,11 +492,17 @@ var BraintrustExporter = class extends BaseExporter {
|
|
|
454
492
|
if (span.output !== void 0) {
|
|
455
493
|
payload.output = this.transformOutput(span.output, span.type);
|
|
456
494
|
}
|
|
495
|
+
if (isCreate && span.isRootSpan && span.tags?.length) {
|
|
496
|
+
payload.tags = span.tags;
|
|
497
|
+
}
|
|
457
498
|
payload.metrics = {};
|
|
458
499
|
payload.metadata = {
|
|
459
|
-
|
|
460
|
-
|
|
500
|
+
...span.metadata,
|
|
501
|
+
spanType: span.type
|
|
461
502
|
};
|
|
503
|
+
if (isCreate) {
|
|
504
|
+
payload.metadata["mastra-trace-id"] = span.traceId;
|
|
505
|
+
}
|
|
462
506
|
const attributes = span.attributes ?? {};
|
|
463
507
|
if (span.type === SpanType.MODEL_GENERATION) {
|
|
464
508
|
const modelAttr = attributes;
|
|
@@ -493,20 +537,9 @@ var BraintrustExporter = class extends BaseExporter {
|
|
|
493
537
|
if (Object.keys(payload.metrics).length === 0) {
|
|
494
538
|
delete payload.metrics;
|
|
495
539
|
}
|
|
540
|
+
payload.metadata = removeNullish(payload.metadata);
|
|
496
541
|
return payload;
|
|
497
542
|
}
|
|
498
|
-
async shutdown() {
|
|
499
|
-
if (!this.config) {
|
|
500
|
-
return;
|
|
501
|
-
}
|
|
502
|
-
for (const [_traceId, spanData] of this.traceMap) {
|
|
503
|
-
for (const [_spanId, span] of spanData.spans) {
|
|
504
|
-
span.end();
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
this.traceMap.clear();
|
|
508
|
-
await super.shutdown();
|
|
509
|
-
}
|
|
510
543
|
};
|
|
511
544
|
|
|
512
545
|
export { BraintrustExporter };
|