Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions packages/evals/framework/braintrust.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
* the callback's value unchanged, so this is safe to call from offline tools
* (e.g., `bench verify`).
*/
import { SpanStatusCode } from "@opentelemetry/api";
import type { Span, StartSpanArgs } from "braintrust";
import { resolveTraceTransport } from "./langsmith.js";

let braintrustPromise: Promise<typeof import("braintrust")> | undefined;

Expand Down Expand Up @@ -37,6 +39,53 @@ const NOOP_SPAN: SpanLike = {
};

export async function tracedSpan<T>(fn: TracedFn<T>, options: TracedSpanOptions): Promise<T> {
if (resolveTraceTransport() === "otel") {
Comment thread
miguelg719 marked this conversation as resolved.
// cappedJsonAttr keeps oversized attrs under the exporter limit; shared with
// otel.ts so there's a single serialization/cap path.
const { getTracer, cappedJsonAttr } = await import("./otel.js");
const input = options.event?.input;
return getTracer().startActiveSpan(
options.name,
{
attributes: {
"langsmith.span.kind": options.type === "llm" ? "llm" : "chain",
...(input === undefined
? {}
: {
"input.value": cappedJsonAttr(input),
"input.mime_type": "application/json",
}),
},
},
async (otelSpan) => {
const span: SpanLike = {
log: (event) => {
if (event.output !== undefined) {
otelSpan.setAttributes({
"output.value": cappedJsonAttr(event.output),
"output.mime_type": "application/json",
});
}
if (event.metadata !== undefined) {
otelSpan.setAttribute("langsmith.metadata", cappedJsonAttr(event.metadata));
}
},
};
try {
return await fn(span);
} catch (error) {
otelSpan.recordException(error instanceof Error ? error : String(error));
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
otelSpan.setStatus({
code: SpanStatusCode.ERROR,
message: error instanceof Error ? error.message : String(error),
});
throw error;
} finally {
otelSpan.end();
}
},
);
}
if (!hasBraintrustApiKey()) {
return fn(NOOP_SPAN);
}
Expand Down
Loading