Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(ui): add csv/json export for scores table (#5949)

Marc Klingenc2f51b8d2d3e
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 48925dd114..b64c6a41c4 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -35,6 +35,7 @@ import {
convertSelectedEnvironmentsToFilter,
} from "@/src/hooks/use-environment-filter";
import { Badge } from "@/src/components/ui/badge";
+import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";
import React, { useState } from "react";
@@ -569,6 +570,11 @@ export default function ScoresTable({
tableName={BatchExportTableName.Scores}
/>
) : null,
+ <BatchExportTableButton
+ {...{ projectId, filterState, orderByState }}
+ tableName={BatchExportTableName.Scores}
+ key="batchExport"
+ />,
]}
rowHeight={rowHeight}
setRowHeight={setRowHeight}
diff --git a/worker/src/__tests__/batchAction.test.ts b/worker/src/__tests__/batchAction.test.ts
index 2fbab9cd35..14f1d13b15 100644
--- a/worker/src/__tests__/batchAction.test.ts
+++ b/worker/src/__tests__/batchAction.test.ts
@@ -1,4 +1,5 @@
import { BatchExportTableName } from "@langfuse/shared";
+import { BatchActionType } from "@langfuse/shared";
import { expect, describe, it, vi } from "vitest";
import { randomUUID } from "crypto";
import { handleBatchActionJob } from "../features/batchAction/handleBatchActionJob";
@@ -140,7 +141,12 @@ describe("select all test suite", () => {
projectId,
actionId: "score-delete",
tableName: BatchExportTableName.Scores,
- query: {},
+ cutoffCreatedAt: new Date(),
+ query: {
+ filter: null,
+ orderBy: { column: "timestamp", order: "DESC" },
+ },
+ type: BatchActionType.Delete,
},
});
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.ts
index a581d4992b..b196d1d03f 100644
--- a/worker/src/__tests__/batchExport.test.ts
+++ b/worker/src/__tests__/batchExport.test.ts
@@ -501,4 +501,414 @@ describe("batch export test suite", () => {
]),
);
});
+
+ it("should export scores with filter and sorting", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create traces to associate scores with
+ const traces = [
+ createTrace({
+ project_id: projectId,
+ id: randomUUID(),
+ name: "trace-for-scores-1",
+ timestamp: new Date("2024-01-01").getTime(),
+ }),
+ createTrace({
+ project_id: projectId,
+ id: randomUUID(),
+ name: "trace-for-scores-2",
+ timestamp: new Date("2024-01-02").getTime(),
+ }),
+ ];
+
+ await createTracesCh(traces);
+
+ // Create observations to associate scores with
+ const observations = [
+ createObservation({
+ project_id: projectId,
+ trace_id: traces[0].id,
+ id: randomUUID(),
+ type: "GENERATION",
+ name: "observation-for-scores-1",
+ }),
+ createObservation({
+ project_id: projectId,
+ trace_id: traces[1].id,
+ id: randomUUID(),
+ type: "GENERATION",
+ name: "observation-for-scores-2",
+ }),
+ ];
+
+ await createObservationsCh(observations);
+
+ // Create scores with different names and values
+ const scores = [
+ createScore({
+ project_id: projectId,
+ trace_id: traces[0].id,
+ observation_id: observations[0].id,
+ name: "accuracy",
+ value: 0.85,
+ timestamp: new Date("2024-01-01").getTime(),
+ }),
+ createScore({
+ project_id: projectId,
+ trace_id: traces[0].id,
+ observation_id: observations[0].id,
+ name: "relevance",
+ value: 0.75,
+ timestamp: new Date("2024-01-01").getTime(),
+ }),
+ createScore({
+ project_id: projectId,
+ trace_id: traces[1].id,
+ observation_id: observations[1].id,
+ name: "accuracy",
+ value: 0.92,
+ timestamp: new Date("2024-01-02").getTime(),
+ }),
+ createScore({
+ project_id: projectId,
+ trace_id: traces[1].id,
+ observation_id: observations[1].id,
+ name: "helpfulness",
+ value: 0.88,
+ timestamp: new Date("2024-01-02").getTime(),
+ }),
+ ];
+
+ await createScoresCh(scores);
+
+ // Export scores with filter on name and sort by timestamp
+ const stream = await getDatabaseReadStream({
+ projectId: projectId,
+ tableName: BatchExportTableName.Scores,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "name",
+ value: ["accuracy", "relevance"],
+ },
+ ],
+ orderBy: { column: "timestamp", order: "ASC" },
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ // Should only include scores with names "accuracy" or "relevance"
+ expect(rows).toHaveLength(3);
+
+ // Verify the scores are sorted by timestamp ASC
+ expect(rows[0].name).toBe("accuracy");
+ expect(rows[0].value).toBe(0.85);
+ expect(rows[0].traceId).toBe(traces[0].id);
+
+ expect(rows[1].name).toBe("relevance");
+ expect(rows[1].value).toBe(0.75);
+ expect(rows[1].traceId).toBe(traces[0].id);
+
+ expect(rows[2].name).toBe("accuracy");
+ expect(rows[2].value).toBe(0.92);
+ expect(rows[2].traceId).toBe(traces[1].id);
+ });
+
+ it("should export scores with qualitative values", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create a trace to associate scores with
+ const trace = createTrace({
+ project_id: projectId,
+ id: randomUUID(),
+ name: "trace-for-qualitative-scores",
+ });
+
+ await createTracesCh([trace]);
+
+ // Create an observation to associate scores with
+ const observation = createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ id: randomUUID(),
+ type: "GENERATION",
+ name: "observation-for-qualitative-scores",
+ });
+
+ await createObservationsCh([observation]);
+
+ // Create scores with string values
+ const scores = [
+ createScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observation.id,
+ name: "category",
+ string_value: "excellent",
+ }),
+ createScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observation.id,
+ name: "feedback",
+ string_value: "The response was very helpful and accurate.",
+ }),
+ ];
+
+ await createScoresCh(scores);
+
+ // Export all scores
+ const stream = await getDatabaseReadStream({
+ projectId: projectId,
+ tableName: BatchExportTableName.Scores,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [],
+ orderBy: { column: "name", order: "ASC" },
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(2);
+
+ // Verify the qualitative scores - just check the essential properties
+ expect(
+ rows.map((row) => ({
+ name: row.name,
+ stringValue: row.stringValue,
+ traceId: row.traceId,
+ })),
+ ).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: "category",
+ stringValue: "excellent",
+ traceId: trace.id,
+ }),
+ expect.objectContaining({
+ name: "feedback",
+ stringValue: "The response was very helpful and accurate.",
+ traceId: trace.id,
+ }),
+ ]),
+ );
+ });
+
+ it("should export scores with date range filtering", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create a trace to associate scores with
+ const trace = createTrace({
+ project_id: projectId,
+ id: randomUUID(),
+ name: "trace-for-date-range",
+ });
+
+ await createTracesCh([trace]);
+
+ // Create an observation to associate scores with
+ const observation = createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ id: randomUUID(),
+ type: "GENERATION",
+ name: "observation-for-date-range",
+ });
+
+ await createObservationsCh([observation]);
+
+ // Create scores with different timestamps
+ const scores = [
+ createScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observation.id,
+ name: "score1",
+ value: 0.5,
+ timestamp: new Date("2024-01-01T10:00:00Z").getTime(),
+ }),
+ createScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observation.id,
+ name: "score2",
+ value: 0.6,
+ timestamp: new Date("2024-01-15T10:00:00Z").getTime(),
+ }),
+ createScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observation.id,
+ name: "score3",
+ value: 0.7,
+ timestamp: new Date("2024-01-30T10:00:00Z").getTime(),
+ }),
+ ];
+
+ await createScoresCh(scores);
+
+ // Export scores with date range filter
+ const stream = await getDatabaseReadStream({
+ projectId: projectId,
+ tableName: BatchExportTableName.Scores,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "datetime",
+ operator: ">=",
+ column: "timestamp",
+ value: new Date("2024-01-10T00:00:00Z"),
+ },
+ {
+ type: "datetime",
+ operator: "<",
+ column: "timestamp",
+ value: new Date("2024-01-20T00:00:00Z"),
+ },
+ ],
+ orderBy: { column: "timestamp", order: "ASC" },
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ // Should only include scores within the date range
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("score2");
+ expect(rows[0].value).toBe(0.6);
+ expect(new Date(rows[0].timestamp).toISOString()).toBe(
+ "2024-01-15T10:00:00.000Z",
+ );
+ });
+
+ it("should export scores with multiple filter conditions", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Create traces to associate scores with
+ const traces = [
+ createTrace({
+ project_id: projectId,
+ id: randomUUID(),
+ name: "trace-multi-filter-1",
+ }),
+ createTrace({
+ project_id: projectId,
+ id: randomUUID(),
+ name: "trace-multi-filter-2",
+ }),
+ ];
+
+ await createTracesCh(traces);
+
+ // Create observations to associate scores with
+ const observations = [
+ createObservation({
+ project_id: projectId,
+ trace_id: traces[0].id,
+ id: randomUUID(),
+ type: "GENERATION",
+ name: "observation-multi-filter-1",
+ }),
+ createObservation({
+ project_id: projectId,
+ trace_id: traces[1].id,
+ id: randomUUID(),
+ type: "GENERATION",
+ name: "observation-multi-filter-2",
+ }),
+ ];
+
+ await createObservationsCh(observations);
+
+ // Create scores with different attributes
+ const scores = [
+ createScore({
+ project_id: projectId,
+ trace_id: traces[0].id,
+ observation_id: observations[0].id,
+ name: "quality",
+ value: 0.7,
+ source: "API",
+ }),
+ createScore({
+ project_id: projectId,
+ trace_id: traces[0].id,
+ observation_id: observations[0].id,
+ name: "quality",
+ value: 0.8,
+ source: "UI",
+ }),
+ createScore({
+ project_id: projectId,
+ trace_id: traces[1].id,
+ observation_id: observations[1].id,
+ name: "quality",
+ value: 0.9,
+ source: "API",
+ }),
+ createScore({
+ project_id: projectId,
+ trace_id: traces[1].id,
+ observation_id: observations[1].id,
+ name: "relevance",
+ value: 0.85,
+ source: "API",
+ }),
+ ];
+
+ await createScoresCh(scores);
+
+ // Export scores with multiple filter conditions
+ const stream = await getDatabaseReadStream({
+ projectId: projectId,
+ tableName: BatchExportTableName.Scores,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "name",
+ value: ["quality"],
+ },
+ {
+ type: "stringOptions",
+ operator: "any of",
+ column: "source",
+ value: ["API"],
+ },
+ {
+ type: "number",
+ operator: ">=",
+ column: "value",
+ value: 0.8,
+ },
+ ],
+ orderBy: { column: "value", order: "ASC" },
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ // Should only include scores that match all filter conditions
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("quality");
+ expect(rows[0].source).toBe("API");
+ expect(rows[0].value).toBe(0.9);
+ expect(rows[0].traceId).toBe(traces[1].id);
+ });
});
diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.ts
index b4356a89cd..bb1cab0372 100644
--- a/worker/src/features/batchExport/handleBatchExportJob.ts
+++ b/worker/src/features/batchExport/handleBatchExportJob.ts
@@ -4,6 +4,7 @@ import {
BatchExportQuerySchema,
BatchExportQueryType,
BatchExportStatus,
+ BatchExportTableName,
exportOptions,
FilterCondition,
TimeFilter,
@@ -15,7 +16,7 @@ import {
StorageServiceFactory,
sendBatchExportSuccessEmail,
streamTransformations,
- BatchExportJobType,
+ type BatchExportJobType,
FullObservationsWithScores,
getPublicSessionsFilter,
getScoresForObservations,
@@ -27,13 +28,14 @@ import {
logger,
getTracesByIds,
getSessionsWithMetrics,
+ type ScoreUiTableRow,
getScoresUiTable,
} from "@langfuse/shared/src/server";
import { env } from "../../env";
import { BatchExportSessionsRow, BatchExportTracesRow } from "./types";
import Decimal from "decimal.js";
-const tableNameToTimeFilterColumn = {
+const tableNameToTimeFilterColumn: Record<BatchExportTableName, string> = {
scores: "timestamp",
sessions: "createdAt",
traces: "timestamp",
@@ -41,7 +43,7 @@ const tableNameToTimeFilterColumn = {
dataset_run_items: "createdAt",
};
-const tableNameToTimeFilterColumnCh = {
+const tableNameToTimeFilterColumnCh: Record<BatchExportTableName, string> = {
scores: "timestamp",
sessions: "createdAt",
traces: "timestamp",
@@ -119,14 +121,34 @@ export const getDatabaseReadStream = async ({
switch (tableName) {
case "scores": {
return new DatabaseReadStream<unknown>(
- async (pageSize: number, offset: number) =>
- getScoresUiTable({
+ async (pageSize: number, offset: number) => {
+ const scores = await getScoresUiTable({
projectId,
- filter: filter ?? [],
+ filter: filter
+ ? [...filter, createdAtCutoffFilter]
+ : [createdAtCutoffFilter],
orderBy,
limit: pageSize,
offset,
- }),
+ });
+
+ return scores.map((score: ScoreUiTableRow) => ({
+ id: score.id,
+ traceId: score.traceId,
+ timestamp: score.timestamp,
+ source: score.source,
+ name: score.name,
+ dataType: score.dataType,
+ value: score.value,
+ stringValue: score.stringValue,
+ comment: score.comment,
+ observationId: score.observationId,
+ traceName: score.traceName,
+ userId: score.traceUserId,
+ traceTags: score.traceTags,
+ environment: score.environment,
+ }));
+ },
1000,
exportLimit,
);