The platform for continuously improving AI agents.
import type { JsonObject, JsonValue } from "@bufbuild/protobuf";
import type { ListValue } from "@bufbuild/protobuf/wkt";
import { listJson } from "@/lib/otel-rpc/format";
export type SpanNote = { key: string; value: JsonValue };
export function spanNotes(
attributes: JsonObject | undefined,
events: ListValue | undefined
): { scores: SpanNote[]; feedback: SpanNote[]; omit: Set<string> } {
return plainSpanNotes(attributes, listJson(events));
}
/** Same classification as `spanNotes`, for spans already decoded into plain records. */
export function plainSpanNotes(
attributes: Record<string, unknown> | undefined,
events: unknown[] = []
): { scores: SpanNote[]; feedback: SpanNote[]; omit: Set<string> } {
const scores: SpanNote[] = [];
const feedback: SpanNote[] = [];
const omit = new Set<string>();
for (const [key, value] of Object.entries(attributes ?? {})) {
const kind = noteKind(key);
if (!kind || value === undefined || value === null || value === "") continue;
omit.add(key);
(kind === "score" ? scores : feedback).push({ key, value: value as JsonValue });
}
for (const event of events) {
if (!event || typeof event !== "object" || Array.isArray(event)) continue;
const record = event as Record<string, unknown>;
const name = typeof record.name === "string" ? record.name : "";
const kind = noteKind(name);
if (!kind || !name) continue;
const value =
record.attributes && typeof record.attributes === "object" ? record.attributes : event;
(kind === "score" ? scores : feedback).push({ key: name, value: value as JsonValue });
}
return { feedback, omit, scores };
}
function noteKind(key: string): "score" | "feedback" | null {
const name = key.toLowerCase();
if (name.includes("feedback") || name.includes("annotation") || name.includes("thumbs"))
return "feedback";
if (
name.includes("evaluation") ||
name.startsWith("eval.") ||
name.includes(".eval.") ||
name === "score" ||
name.endsWith(".score") ||
name.includes("eval_score")
) {
return "score";
}
return null;
}