Skip to content

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

feat(scores): implement internal changes for `TEXT` (free form) scores (#12902)

Tobias Wochinger859c58e96ca3
diff --git a/packages/shared/prisma/migrations/20260327000000_add_free_form_score_config_data_type/migration.sql b/packages/shared/prisma/migrations/20260327000000_add_free_form_score_config_data_type/migration.sql
new file mode 100644
index 0000000000..cc338d12fa
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260327000000_add_free_form_score_config_data_type/migration.sql
@@ -0,0 +1,2 @@
+-- AlterEnum
+ALTER TYPE "ScoreConfigDataType" ADD VALUE 'TEXT';
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index d2975012f7..6dad38b481 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -495,6 +495,7 @@ enum ScoreConfigDataType {
CATEGORICAL
NUMERIC
BOOLEAN
+ TEXT
}
model AnnotationQueue {
@@ -924,7 +925,7 @@ model EvalTemplate {
provider String?
modelParams Json? @map("model_params")
vars String[] @default([])
- outputDefinition Json @map("output_schema")
+ outputDefinition Json @map("output_schema")
JobConfiguration JobConfiguration[]
JobExecution JobExecution[]
diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.ts
index c154bc5909..db857762b9 100644
--- a/packages/shared/scripts/seeder/seed-postgres.ts
+++ b/packages/shared/scripts/seeder/seed-postgres.ts
@@ -965,6 +965,14 @@ async function generateConfigs(project: Project) {
"Used to indicate if text was harmful or offensive in nature.",
isArchived: false,
},
+ {
+ id: `config-${v4()}`,
+ projectId: project.id,
+ name: "Feedback",
+ dataType: ScoreDataTypeEnum.TEXT,
+ description: "Free-form text feedback on the output quality.",
+ isArchived: false,
+ },
];
for (const config of configs) {
diff --git a/packages/shared/src/domain/score-configs.ts b/packages/shared/src/domain/score-configs.ts
index 2e69a3d486..58871eef5c 100644
--- a/packages/shared/src/domain/score-configs.ts
+++ b/packages/shared/src/domain/score-configs.ts
@@ -72,6 +72,13 @@ export const CategoricalConfigFields = z.object({
categories: z.array(ScoreConfigCategory).superRefine(validateCategories),
});
+export const TextConfigFields = z.object({
+ maxValue: z.undefined().nullish(),
+ minValue: z.undefined().nullish(),
+ dataType: z.literal("TEXT"),
+ categories: z.undefined().nullish(),
+});
+
const ScoreConfigBase = z.object({
id: z.string(),
name: z.string().min(1).max(35),
@@ -114,6 +121,10 @@ export const ScoreConfigSchema = z
...ScoreConfigBase.shape,
...BooleanConfigFields.shape,
}),
+ z.object({
+ ...ScoreConfigBase.shape,
+ ...TextConfigFields.shape,
+ }),
])
.superRefine(validateNumericRangeFields);
diff --git a/packages/shared/src/domain/scores.ts b/packages/shared/src/domain/scores.ts
index 90a60f71dc..e93a42706a 100644
--- a/packages/shared/src/domain/scores.ts
+++ b/packages/shared/src/domain/scores.ts
@@ -12,17 +12,21 @@ export type ScoreSourceType = z.infer<typeof ScoreSourceDomain>;
export const CORRECTION_NAME = "output" as const;
+export const TEXT_SCORE_MAX_LENGTH = 500 as const;
+
export const ScoreDataTypeArray = [
"NUMERIC",
"CATEGORICAL",
"BOOLEAN",
"CORRECTION",
+ "TEXT",
] as const;
export const ScoreDataTypeEnum = {
NUMERIC: "NUMERIC",
CATEGORICAL: "CATEGORICAL",
BOOLEAN: "BOOLEAN",
CORRECTION: "CORRECTION",
+ TEXT: "TEXT",
} as const;
export const ScoreDataTypeDomain = z.enum(ScoreDataTypeArray);
export type ScoreDataTypeType = z.infer<typeof ScoreDataTypeDomain>;
@@ -47,6 +51,11 @@ const CorrectionData = z.object({
dataType: z.literal("CORRECTION"),
});
+export const TextData = z.object({
+ stringValue: z.string().min(1).max(TEXT_SCORE_MAX_LENGTH),
+ dataType: z.literal("TEXT"),
+});
+
// Only used for backwards compatibility with old score API schemas
export const ScoreSchemaExclReferencesAndDates = z.object({
// Core identifiers
@@ -89,6 +98,7 @@ export const ScoreSchema = ScoreFoundationSchema.and(
CategoricalData,
BooleanData,
CorrectionData,
+ TextData,
]),
);
@@ -119,3 +129,10 @@ export type AggregatableScoreDataType =
export type AggregatableScore = ScoresByDataTypes<
typeof AGGREGATABLE_SCORE_TYPES
>;
+
+export const LISTABLE_SCORE_TYPES = ScoreDataTypeArray.filter(
+ (type) => type !== "CORRECTION",
+) satisfies readonly ScoreDataTypeType[];
+
+export type ListableScoreDataType = (typeof LISTABLE_SCORE_TYPES)[number];
+export type ListableScore = ScoresByDataTypes<typeof LISTABLE_SCORE_TYPES>;
diff --git a/packages/shared/src/features/annotation/types.ts b/packages/shared/src/features/annotation/types.ts
index d41ce1ba77..c5848f961e 100644
--- a/packages/shared/src/features/annotation/types.ts
+++ b/packages/shared/src/features/annotation/types.ts
@@ -1,6 +1,11 @@
import z from "zod";
import { StringNoHTML, StringNoHTMLNonEmpty } from "../../utils/zod";
-import { BooleanData, CategoricalData, NumericData } from "../../domain";
+import {
+ BooleanData,
+ CategoricalData,
+ TextData,
+ NumericData,
+} from "../../domain";
const ScoreTargetTrace = z.object({
type: z.literal("trace"),
@@ -45,7 +50,12 @@ const UpdateAnnotationScoreBase = CreateAnnotationScoreBase.extend({
* For langfuse score types please refer to `web/src/features/public-api/types/scores.ts`
*/
export const CreateAnnotationScoreData = CreateAnnotationScoreBase.and(
- z.discriminatedUnion("dataType", [NumericData, CategoricalData, BooleanData]),
+ z.discriminatedUnion("dataType", [
+ NumericData,
+ CategoricalData,
+ BooleanData,
+ TextData,
+ ]),
);
export type CreateAnnotationScoreData = z.infer<
@@ -57,7 +67,12 @@ export type CreateAnnotationScoreData = z.infer<
* For langfuse score types please refer to `web/src/features/public-api/types/scores.ts`
*/
export const UpdateAnnotationScoreData = UpdateAnnotationScoreBase.and(
- z.discriminatedUnion("dataType", [NumericData, CategoricalData, BooleanData]),
+ z.discriminatedUnion("dataType", [
+ NumericData,
+ CategoricalData,
+ BooleanData,
+ TextData,
+ ]),
);
export type UpdateAnnotationScoreData = z.infer<
diff --git a/packages/shared/src/features/scores/interfaces/ingestion/validation.ts b/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
index 1fd5bdad91..2ff685cae1 100644
--- a/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
+++ b/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
@@ -3,6 +3,7 @@ import { applyScoreValidation } from "../../../../utils/scores";
import { PostScoreBodyFoundationSchema } from "../shared";
import { isPresent } from "../../../../utils/typeChecks";
import { ScoreConfigCategory } from "../../../../domain/score-configs";
+import { TEXT_SCORE_MAX_LENGTH } from "../../../../domain/scores";
export const ScoreBodyWithoutConfig = applyScoreValidation(
z.discriminatedUnion("dataType", [
@@ -81,4 +82,8 @@ export const ScorePropsAgainstConfig = z.union([
}),
dataType: z.literal("BOOLEAN"),
}),
+ z.object({
+ value: z.string().min(1).max(TEXT_SCORE_MAX_LENGTH),
+ dataType: z.literal("TEXT"),
+ }),
]);
diff --git a/packages/shared/src/features/scores/interfaces/ui/types.ts b/packages/shared/src/features/scores/interfaces/ui/types.ts
index 12798e15a0..7c94f97626 100644
--- a/packages/shared/src/features/scores/interfaces/ui/types.ts
+++ b/packages/shared/src/features/scores/interfaces/ui/types.ts
@@ -1,5 +1,5 @@
import {
- AggregatableScoreDataType,
+ ListableScoreDataType,
MetadataDomain,
ScoreSourceType,
} from "../../../../domain";
@@ -30,7 +30,7 @@ export type ScoreAggregate = Record<string, AggregatedScoreData>;
export type ScoreSimplified = {
id: string;
name: string;
- dataType: AggregatableScoreDataType;
+ dataType: ListableScoreDataType;
source: ScoreSourceType;
value?: number | null;
comment?: string | null;
diff --git a/packages/shared/src/server/ingestion/validateAndInflateScore.ts b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
index f5634c10e4..788d540507 100644
--- a/packages/shared/src/server/ingestion/validateAndInflateScore.ts
+++ b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
@@ -141,6 +141,15 @@ function inflateScoreBody(
};
}
+ if (relevantDataType === ScoreDataTypeEnum.TEXT) {
+ return {
+ ...scoreProps,
+ value: 0,
+ stringValue: body.value,
+ dataType: ScoreDataTypeEnum.TEXT,
+ };
+ }
+
return {
...scoreProps,
value: config ? mapStringValueToNumericValue(config, body.value) : 0,
@@ -173,6 +182,7 @@ function resolveScoreValueAnnotation(
case ScoreDataTypeEnum.BOOLEAN:
return body.value;
case ScoreDataTypeEnum.CATEGORICAL:
+ case ScoreDataTypeEnum.TEXT:
return body.stringValue;
case ScoreDataTypeEnum.CORRECTION:
throw new Error("CORRECTION type not supported in annotation drawer");
diff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
index 60d0084624..677562a797 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
@@ -74,7 +74,7 @@ interface BaseScoresAggregationParams extends BaseScoresParams {
hasScoreAggregationFilters?: boolean;
/**
* When true, adds an extra `score_categories_tuples` column with
- * `tuple(name, string_value)` encoding alongside the default concat-encoded
+ * `tuple(name, string_value, data_type)` encoding alongside the default concat-encoded
* `score_categories`. The tuple column is safe for programmatic parsing
* (e.g. batch exports) when score names may contain colons.
* The concat column is always present for hasAny filter compatibility.
@@ -120,7 +120,7 @@ export const buildScoresAggregationCTE = (
${primaryKey},
${additionalOuterCols.length > 0 ? additionalOuterCols.join(",\n ") + "," : ""}
groupArrayIf(tuple(name, avg_value, data_type, string_value), data_type IN ('NUMERIC', 'BOOLEAN')) AS scores_avg,
- groupArrayIf(concat(name, ':', string_value), data_type = 'CATEGORICAL' AND notEmpty(string_value)) AS score_categories${params.includeTupleEncoding ? `,\n groupArrayIf(tuple(name, string_value), data_type = 'CATEGORICAL' AND notEmpty(string_value)) AS score_categories_tuples` : ""}
+ groupArrayIf(concat(name, ':', string_value), data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)) AS score_categories${params.includeTupleEncoding ? `,\n groupArrayIf(tuple(name, string_value, data_type), data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)) AS score_categories_tuples` : ""}
FROM (
SELECT
${primaryKey},
@@ -319,7 +319,7 @@ export const eventsSessionScoresAggregation = (params: {
) AS scores_avg,
groupArrayIf(
concat(name, ':', string_value),
- data_type = 'CATEGORICAL' AND notEmpty(string_value)
+ data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)
) AS score_categories
FROM (
SELECT
diff --git a/packages/shared/src/server/repositories/environments.ts b/packages/shared/src/server/repositories/environments.ts
index 1e2148ad93..5217292e05 100644
--- a/packages/shared/src/server/repositories/environments.ts
+++ b/packages/shared/src/server/repositories/environments.ts
@@ -1,4 +1,4 @@
-import { AGGREGATABLE_SCORE_TYPES } from "../../domain/scores";
+import { LISTABLE_SCORE_TYPES } from "../../domain/scores";
import { queryClickhouse } from "./clickhouse";
export type EnvironmentFilterProps = {
@@ -38,7 +38,7 @@ export const getEnvironmentsForProject = async (
params: {
projectId,
fromTimestamp,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
},
tags: {
feature: "tracing",
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index ed66083ee1..a6ec4f186e 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -5,6 +5,8 @@ import {
AGGREGATABLE_SCORE_TYPES,
AggregatableScoreDataType,
ScoreByDataType,
+ LISTABLE_SCORE_TYPES,
+ ListableScoreDataType,
} from "../../domain/scores";
import {
commandClickhouse,
@@ -131,7 +133,7 @@ export const getScoresByIds = async (
scoreId,
source,
scoreScope: "all",
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
});
};
@@ -249,7 +251,7 @@ export const getScoresForSessions = async <
sessionIds,
limit,
offset,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
},
tags: {
feature: "sessions",
@@ -594,7 +596,7 @@ export const getScoresForTraces = async <
) => {
return getScoresForTracesInternal({
...props,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
});
};
@@ -673,7 +675,7 @@ export const getScoresForObservations = async <
params: {
projectId: projectId,
observationIds: observationIds,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
limit: limit,
offset: offset,
},
@@ -809,7 +811,7 @@ export const getScoresGroupedByNameSourceType = async ({
query: query,
params: {
projectId: projectId,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
...(fromTimestamp
? { fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp) }
: {}),
@@ -832,7 +834,7 @@ export const getScoresGroupedByNameSourceType = async ({
return rows.map((row) => ({
name: row.name,
source: row.source as ScoreSourceType,
- dataType: row.data_type as AggregatableScoreDataType,
+ dataType: row.data_type as ListableScoreDataType,
}));
};
@@ -1189,7 +1191,7 @@ const getScoresUiGeneric = async <T>(props: {
input: {
params: {
projectId: projectId,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
...(scoresFilterRes ? scoresFilterRes.params : {}),
limit: limit,
offset: offset,
@@ -1393,7 +1395,7 @@ const getScoresUiGenericFromEvents = async <T>(props: {
input: {
params: {
projectId,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
...(scoreOnlyFilterRes ? scoreOnlyFilterRes.params : {}),
...tracesCTEParams,
limit,
@@ -1535,7 +1537,7 @@ export const getScoreNames = async (
params: {
projectId: projectId,
...(timestampFilterRes ? timestampFilterRes.params : {}),
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
},
tags: {
feature: "tracing",
@@ -1564,6 +1566,8 @@ export const getScoreStringValues = async (
);
const timestampFilterRes = chFilter.apply();
+ // exclude TEXT scores as they are arbitrary by nature and hence have high cardinality
+ // which in turn can lead to performance issues
const query = `
select
string_value,
@@ -1572,6 +1576,7 @@ export const getScoreStringValues = async (
WHERE s.project_id = {projectId: String}
AND string_value IS NOT NULL
AND string_value != ''
+ AND s.data_type != 'TEXT'
${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
GROUP BY string_value
ORDER BY count() desc
@@ -1838,7 +1843,7 @@ export const getAggregatedScoresForPrompts = async (
params: {
projectId,
promptIds,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
},
tags: {
feature: "tracing",
@@ -1849,7 +1854,7 @@ export const getAggregatedScoresForPrompts = async (
});
return rows.map((row) => ({
- ...convertScoreAggregation<AggregatableScoreDataType>(row),
+ ...convertScoreAggregation<ListableScoreDataType>(row),
promptId: row.prompt_id,
hasMetadata: !!row.has_metadata,
}));
@@ -1878,7 +1883,7 @@ export const getScoreCountsByProjectInCreationInterval = async ({
params: {
start: convertDateToClickhouseDateTime(start),
end: convertDateToClickhouseDateTime(end),
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
},
clickhouseConfigs: {
request_timeout: 120000, // 2 minutes timeout
@@ -1957,7 +1962,7 @@ export const getDistinctScoreNames = async (p: {
params: {
projectId,
cutoffCreatedAt: convertDateToClickhouseDateTime(cutoffCreatedAt),
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
...(scoreTimestampFilter
? {
filterTimestamp: convertDateToClickhouseDateTime(
@@ -2014,7 +2019,7 @@ export const getScoresForBlobStorageExport = function (
projectId,
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
},
tags: {
feature: "blobstorage",
@@ -2087,7 +2092,7 @@ export const getScoresForAnalyticsIntegrations = async function* (
projectId,
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
},
tags: {
feature: "posthog",
@@ -2260,7 +2265,7 @@ export const getScoreCountsByProjectAndDay = async ({
params: {
startDate: convertDateToClickhouseDateTime(startDate),
endDate: convertDateToClickhouseDateTime(endDate),
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
},
tags: {
feature: "tracing",
diff --git a/web/src/__tests__/server/repositories/score-repository.servertest.ts b/web/src/__tests__/server/repositories/score-repository.servertest.ts
index 81b66e24fb..ddc5c99e39 100644
--- a/web/src/__tests__/server/repositories/score-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/score-repository.servertest.ts
@@ -2,11 +2,15 @@ import { prisma } from "@langfuse/shared/src/db";
import {
createScoresCh,
getScoreById,
+ getScoresByIds,
getScoresGroupedByNameSourceType,
getScoresUiTable,
getScoresForTraces,
getScoresForObservations,
getScoresForSessions,
+ getScoresForExperiments,
+ getTraceScoresForDatasetRuns,
+ getScoreNames,
createTracesCh,
createObservationsCh,
createTrace,
@@ -17,6 +21,7 @@ import {
createDatasetRunScore,
createSessionScore,
createOrgProjectAndApiKey,
+ getScoreStringValues,
} from "@langfuse/shared/src/server";
import { v4 } from "uuid";
@@ -798,4 +803,350 @@ describe("Clickhouse Scores Repository Test", () => {
expect(result[0].metadata).toEqual({});
});
});
+
+ describe("TEXT scores", () => {
+ it("should round-trip a TEXT score through ClickHouse", async () => {
+ const scoreId = v4();
+ const traceId = v4();
+
+ const score = createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ trace_id: traceId,
+ name: "free-form-score",
+ value: 0,
+ string_value: "This is free text feedback",
+ data_type: "TEXT",
+ source: "ANNOTATION",
+ });
+
+ await createScoresCh([score]);
+
+ const result = await getScoreById({ projectId, scoreId });
+ expect(result).toBeDefined();
+ expect(result!.dataType).toBe("TEXT");
+ expect(result!.stringValue).toBe("This is free text feedback");
+ expect(result!.value).toBe(0);
+ expect(result!.source).toBe("ANNOTATION");
+ });
+
+ it("should include TEXT scores in getScoresGroupedByNameSourceType", async () => {
+ const isolatedProjectId = v4();
+ const traceId = v4();
+
+ const numericScore = createTraceScore({
+ project_id: isolatedProjectId,
+ trace_id: traceId,
+ name: "numeric-score",
+ data_type: "NUMERIC",
+ value: 42,
+ source: "API",
+ });
+
+ const textScore = createTraceScore({
+ project_id: isolatedProjectId,
+ trace_id: traceId,
+ name: "free-form-score",
+ data_type: "TEXT",
+ value: 0,
+ string_value: "Some feedback text",
+ source: "ANNOTATION",
+ });
+
+ await createScoresCh([numericScore, textScore]);
+
+ const result = await getScoresGroupedByNameSourceType({
+ projectId: isolatedProjectId,
+ filter: [],
+ });
+
+ expect(result).toHaveLength(2);
+ expect(result).toEqual([
+ {
+ name: "free-form-score",
+ source: "ANNOTATION",
+ dataType: "TEXT",
+ },
+ {
+ name: "numeric-score",
+ source: "API",
+ dataType: "NUMERIC",
+ },
+ ]);
+ });
+
+ it("should exclude TEXT string values from getScoreStringValues", async () => {
+ const isolatedProjectId = v4();
+ const traceId = v4();
+
+ const categoricalScore = createTraceScore({
+ project_id: isolatedProjectId,
+ trace_id: traceId,
+ name: "cat-score",
+ data_type: "CATEGORICAL",
+ value: 1,
+ string_value: "Good",
+ source: "API",
+ });
+
+ const textScore = createTraceScore({
+ project_id: isolatedProjectId,
+ trace_id: traceId,
+ name: "free-text-score",
+ data_type: "TEXT",
+ value: 0,
+ string_value: "This should not appear in filter options",
+ source: "ANNOTATION",
+ });
+
+ await createScoresCh([categoricalScore, textScore]);
+
+ const result = await getScoreStringValues(isolatedProjectId, []);
+
+ const stringValues = result.map((r) => r.value);
+ expect(stringValues).toContain("Good");
+ expect(stringValues).not.toContain(
+ "This should not appear in filter options",
+ );
+ });
+ });
+
+ describe("score data type coverage", () => {
+ let isolatedProjectId: string;
+ const traceId = v4();
+ const observationId = v4();
+ const sessionId = v4();
+ const scoreIds: string[] = [];
+
+ beforeAll(async () => {
+ const { projectId: pid } = await createOrgProjectAndApiKey();
+ isolatedProjectId = pid;
+
+ const trace = createTrace({
+ id: traceId,
+ project_id: isolatedProjectId,
+ session_id: sessionId,
+ });
+ await createTracesCh([trace]);
+
+ const obs = createObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: isolatedProjectId,
+ });
+ await createObservationsCh([obs]);
+
+ const scores = [
+ createTraceScore({
+ project_id: isolatedProjectId,
+ trace_id: traceId,
+ observation_id: observationId,
+ name: "numeric",
+ data_type: "NUMERIC",
+ value: 1,
+ source: "API",
+ }),
+ createTraceScore({
+ project_id: isolatedProjectId,
+ trace_id: traceId,
+ observation_id: observationId,
+ name: "categorical",
+ data_type: "CATEGORICAL",
+ value: 0,
+ string_value: "Good",
+ source: "API",
+ }),
+ createTraceScore({
+ project_id: isolatedProjectId,
+ trace_id: traceId,
+ observation_id: observationId,
+ name: "boolean",
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "True",
+ source: "API",
+ }),
+ createTraceScore({
+ project_id: isolatedProjectId,
+ trace_id: traceId,
+ observation_id: observationId,
+ name: "free-form",
+ data_type: "TEXT",
+ value: 0,
+ string_value: "Some feedback",
+ source: "ANNOTATION",
+ }),
+ ];
+
+ scoreIds.push(...scores.map((s) => s.id));
+
+ const sessionScores = [
+ createSessionScore({
+ project_id: isolatedProjectId,
+ session_id: sessionId,
+ name: "session-numeric",
+ data_type: "NUMERIC",
+ value: 5,
+ source: "API",
+ }),
+ createSessionScore({
+ project_id: isolatedProjectId,
+ session_id: sessionId,
+ name: "session-free-form",
+ data_type: "TEXT",
+ value: 0,
+ string_value: "Session feedback",
+ source: "ANNOTATION",
+ }),
+ ];
+
+ await createScoresCh([...scores, ...sessionScores]);
+ });
+
+ it("getScoresByIds should return all non-CORRECTION types", async () => {
+ const result = await getScoresByIds(isolatedProjectId, scoreIds);
+ expect(result).toHaveLength(4);
+ });
+
+ it("getScoresForTraces should return all non-CORRECTION types", async () => {
+ const result = await getScoresForTraces({
+ projectId: isolatedProjectId,
+ traceIds: [traceId],
+ });
+ expect(result).toHaveLength(4);
+ });
+
+ it("getScoresForObservations should return all non-CORRECTION types", async () => {
+ const result = await getScoresForObservations({
+ projectId: isolatedProjectId,
+ observationIds: [observationId],
+ });
+ expect(result).toHaveLength(4);
+ });
+
+ it("getScoresForSessions should return all non-CORRECTION types", async () => {
+ const result = await getScoresForSessions({
+ projectId: isolatedProjectId,
+ sessionIds: [sessionId],
+ });
+ expect(result).toHaveLength(2);
+ });
+
+ it("getScoreNames should return names of all non-CORRECTION types", async () => {
+ const result = await getScoreNames(isolatedProjectId, []);
+ const names = result.map((r) => r.name);
+ expect(names).toContain("numeric");
+ expect(names).toContain("categorical");
+ expect(names).toContain("boolean");
+ expect(names).toContain("free-form");
+ });
+
+ it("getScoresGroupedByNameSourceType should return all listable score types", async () => {
+ const result = await getScoresGroupedByNameSourceType({
+ projectId: isolatedProjectId,
+ filter: [],
+ });
+ const dataTypes = result.map((r) => r.dataType);
+ expect(dataTypes).toContain("NUMERIC");
+ expect(dataTypes).toContain("CATEGORICAL");
+ expect(dataTypes).toContain("BOOLEAN");
+ expect(dataTypes).toContain("TEXT");
+ });
+
+ it("getScoresForExperiments should exclude TEXT scores", async () => {
+ const dataset = await prisma.dataset.create({
+ data: { projectId: isolatedProjectId, name: v4() },
+ });
+ const datasetRun = await prisma.datasetRuns.create({
+ data: {
+ projectId: isolatedProjectId,
+ name: v4(),
+ datasetId: dataset.id,
+ },
+ });
+
+ const scores = [
+ createDatasetRunScore({
+ project_id: isolatedProjectId,
+ dataset_run_id: datasetRun.id,
+ name: "run-numeric",
+ data_type: "NUMERIC",
+ value: 1,
+ }),
+ createDatasetRunScore({
+ project_id: isolatedProjectId,
+ dataset_run_id: datasetRun.id,
+ name: "run-free-form",
+ data_type: "TEXT",
+ value: 0,
+ string_value: "Should be excluded",
+ }),
+ ];
+ await createScoresCh(scores);
+
+ const result = await getScoresForExperiments({
+ projectId: isolatedProjectId,
+ runIds: [datasetRun.id],
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].dataType).toBe("NUMERIC");
+ });
+
+ it("getTraceScoresForDatasetRuns should exclude TEXT scores", async () => {
+ const dataset = await prisma.dataset.create({
+ data: { projectId: isolatedProjectId, name: v4() },
+ });
+ const datasetRun = await prisma.datasetRuns.create({
+ data: {
+ projectId: isolatedProjectId,
+ name: v4(),
+ datasetId: dataset.id,
+ },
+ });
+ const runTraceId = v4();
+ const runTrace = createTrace({
+ id: runTraceId,
+ project_id: isolatedProjectId,
+ });
+ await createTracesCh([runTrace]);
+
+ const datasetRunItem = createDatasetRunItem({
+ project_id: isolatedProjectId,
+ dataset_run_id: datasetRun.id,
+ dataset_id: dataset.id,
+ dataset_run_name: datasetRun.name,
+ dataset_item_id: v4(),
+ trace_id: runTraceId,
+ });
+ await createDatasetRunItemsCh([datasetRunItem]);
+
+ const scores = [
+ createTraceScore({
+ project_id: isolatedProjectId,
+ trace_id: runTraceId,
+ name: "trace-boolean",
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "True",
+ }),
+ createTraceScore({
+ project_id: isolatedProjectId,
+ trace_id: runTraceId,
+ name: "trace-free-form",
+ data_type: "TEXT",
+ value: 0,
+ string_value: "Should be excluded",
+ }),
+ ];
+ await createScoresCh(scores);
+
+ const result = await getTraceScoresForDatasetRuns(isolatedProjectId, [
+ datasetRun.id,
+ ]);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].dataType).toBe("BOOLEAN");
+ });
+ });
});
diff --git a/web/src/__tests__/server/validate-config-against-body.servertest.ts b/web/src/__tests__/server/validate-config-against-body.servertest.ts
new file mode 100644
index 0000000000..2f1c5c85c1
--- /dev/null
+++ b/web/src/__tests__/server/validate-config-against-body.servertest.ts
@@ -0,0 +1,133 @@
+/** @jest-environment node */
+
+import {
+ validateConfigAgainstBody,
+ type ScoreConfigDomain,
+ type ScoreDomain,
+} from "@langfuse/shared/src/server";
+
+const baseTextConfig: ScoreConfigDomain = {
+ id: "config-1",
+ name: "free-text-config",
+ dataType: "TEXT",
+ isArchived: false,
+ description: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ projectId: "project-1",
+ maxValue: undefined,
+ minValue: undefined,
+ categories: undefined,
+};
+
+const baseTextScore: ScoreDomain = {
+ id: "score-1",
+ projectId: "project-1",
+ name: "free-text-config",
+ value: 0,
+ stringValue: "Some valid free text",
+ dataType: "TEXT",
+ source: "ANNOTATION",
+ comment: null,
+ metadata: {},
+ configId: "config-1",
+ queueId: null,
+ executionTraceId: null,
+ authorUserId: null,
+ environment: "default",
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ timestamp: new Date(),
+ traceId: "trace-1",
+ sessionId: null,
+ observationId: null,
+ datasetRunId: null,
+ longStringValue: "",
+};
+
+describe("validateConfigAgainstBody for TEXT scores", () => {
+ it("should succeed with valid TEXT annotation score", () => {
+ expect(() =>
+ validateConfigAgainstBody({
+ body: baseTextScore,
+ config: baseTextConfig,
+ context: "ANNOTATION",
+ }),
+ ).not.toThrow();
+ });
+
+ it("should reject empty TEXT text", () => {
+ const emptyScore: ScoreDomain = {
+ ...baseTextScore,
+ stringValue: "",
+ };
+
+ expect(() =>
+ validateConfigAgainstBody({
+ body: emptyScore,
+ config: baseTextConfig,
+ context: "ANNOTATION",
+ }),
+ ).toThrow();
+ });
+
+ it("should reject TEXT text exceeding 500 characters", () => {
+ const longScore: ScoreDomain = {
+ ...baseTextScore,
+ stringValue: "a".repeat(501),
+ };
+
+ expect(() =>
+ validateConfigAgainstBody({
+ body: longScore,
+ config: baseTextConfig,
+ context: "ANNOTATION",
+ }),
+ ).toThrow();
+ });
+
+ it("should accept TEXT text at exactly 500 characters", () => {
+ const maxLengthScore: ScoreDomain = {
+ ...baseTextScore,
+ stringValue: "a".repeat(500),
+ };
+
+ expect(() =>
+ validateConfigAgainstBody({
+ body: maxLengthScore,
+ config: baseTextConfig,
+ context: "ANNOTATION",
+ }),
+ ).not.toThrow();
+ });
+
+ it("should reject archived config", () => {
+ const archivedConfig: ScoreConfigDomain = {
+ ...baseTextConfig,
+ isArchived: true,
+ };
+
+ expect(() =>
+ validateConfigAgainstBody({
+ body: baseTextScore,
+ config: archivedConfig,
+ context: "ANNOTATION",
+ }),
+ ).toThrow("Config is archived");
+ });
+
+ it("should reject name mismatch", () => {
+ const mismatchedScore: ScoreDomain = {
+ ...baseTextScore,
+ name: "different-name",
+ };
+
+ expect(() =>
+ validateConfigAgainstBody({
+ body: mismatchedScore,
+ config: baseTextConfig,
+ context: "ANNOTATION",
+ }),
+ ).toThrow("Name mismatch");
+ });
+});
diff --git a/web/src/components/grouped-score-badge.tsx b/web/src/components/grouped-score-badge.tsx
index 87e0c36faf..bea285ba0e 100644
--- a/web/src/components/grouped-score-badge.tsx
+++ b/web/src/components/grouped-score-badge.tsx
@@ -65,24 +65,26 @@ const ScoreGroupBadge = <
<Badge
variant="tertiary"
key={name}
- className={`flex items-center gap-1 ${compact ? "px-1.5 leading-tight" : "px-2.5"} text-xs font-normal${badgeClassName ? " " + badgeClassName : ""}`}
+ className={`flex max-w-full min-w-0 items-center gap-1 ${compact ? "px-1.5 leading-tight" : "px-2.5"} text-xs font-normal${badgeClassName ? " " + badgeClassName : ""}`}
>
<div
- className={`w-fit max-w-20 truncate ${compact ? "leading-tight" : ""}`}
+ className={`w-fit max-w-20 shrink-0 truncate ${compact ? "leading-tight" : ""}`}
title={name}
>
{name}:
</div>
- <div className="flex items-center gap-1 text-nowrap">
+ <div className="flex min-w-0 items-center gap-1 text-nowrap">
{scores.map((s, i) => (
<span
key={i}
- className="group/score ml-1 flex items-center gap-1 rounded-sm first:ml-0"
+ className="group/score ml-1 flex min-w-0 items-center gap-1 rounded-sm first:ml-0"
>
- {s.stringValue ?? s.value?.toFixed(2) ?? ""}
+ <span className="truncate">
+ {s.stringValue ?? s.value?.toFixed(2) ?? ""}
+ </span>
{s.comment && (
<HoverCard>
- <HoverCardTrigger className="inline-block">
+ <HoverCardTrigger className="inline-block shrink-0">
<MessageCircleMoreIcon className="mb-0.25 size-3!" />
</HoverCardTrigger>
<HoverCardContent className="max-h-[50dvh] overflow-y-auto text-xs break-normal whitespace-normal">
@@ -104,7 +106,7 @@ const ScoreGroupBadge = <
)}
{hasMetadata(s) && (
<HoverCard>
- <HoverCardTrigger className="inline-block">
+ <HoverCardTrigger className="inline-block shrink-0">
<BracesIcon className="mb-0.25 size-3!" />
</HoverCardTrigger>
<HoverCardContent className="max-h-[50dvh] overflow-y-auto rounded-md border-none p-0 text-xs break-normal whitespace-normal">
diff --git a/web/src/components/scores-table-cell.tsx b/web/src/components/scores-table-cell.tsx
index 33f13520e7..47cfb6fcb3 100644
--- a/web/src/components/scores-table-cell.tsx
+++ b/web/src/components/scores-table-cell.tsx
@@ -74,12 +74,15 @@ export const ScoresTableCell = ({
return (
<span
- className={cn("flex flex-row gap-0.5 rounded-sm", COLOR_MAP.get(value))}
+ className={cn(
+ "flex min-w-0 flex-row gap-0.5 rounded-sm",
+ COLOR_MAP.get(value),
+ )}
>
- {value}
+ <span className="truncate">{value}</span>
{aggregate.comment && (
<HoverCard>
- <HoverCardTrigger className="inline-block cursor-pointer">
+ <HoverCardTrigger className="inline-block shrink-0 cursor-pointer">
<MessageCircleMore size={12} />
</HoverCardTrigger>
<HoverCardContent className="flex flex-col p-0 text-xs break-normal whitespace-normal">
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 7ffa174cf8..d4ff42510a 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -29,6 +29,7 @@ import {
isPresent,
type FilterState,
type ScoreDataTypeType,
+ LISTABLE_SCORE_TYPES,
BatchExportTableName,
BatchActionType,
TableViewPresetTableName,
@@ -263,7 +264,7 @@ export default function ScoresTable({
count: n.count !== undefined ? Number(n.count) : undefined,
})) ?? undefined,
source: ["ANNOTATION", "API", "EVAL"],
- dataType: ["NUMERIC", "CATEGORICAL", "BOOLEAN"],
+ dataType: LISTABLE_SCORE_TYPES,
value: [],
stringValue:
filterOptions.data?.stringValue?.map((sv) => ({
diff --git a/web/src/features/events/hooks/useEventsTraceData.ts b/web/src/features/events/hooks/useEventsTraceData.ts
index 6f216a0b7b..8d977840e5 100644
--- a/web/src/features/events/hooks/useEventsTraceData.ts
+++ b/web/src/features/events/hooks/useEventsTraceData.ts
@@ -6,7 +6,7 @@ import {
} from "@/src/features/events/lib/eventsToTraceAdapter";
import {
filterAndValidateDbScoreList,
- AGGREGATABLE_SCORE_TYPES,
+ ScoreDataTypeArray,
ScoreDataTypeEnum,
type ScoreDomain,
} from "@langfuse/shared";
@@ -123,7 +123,7 @@ export function useEventsTraceData(
// Validate and partition scores
const validatedScores = filterAndValidateDbScoreList({
scores: scoresQuery.data ?? [],
- dataTypes: [...AGGREGATABLE_SCORE_TYPES, ScoreDataTypeEnum.CORRECTION],
+ dataTypes: [...ScoreDataTypeArray],
onParseError: (e) => {
console.error("[useEventsTraceData] Score validation error:", e);
},
diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.ts
index a19f3241f6..d2cd6b1e5c 100644
--- a/web/src/features/events/server/eventsService.ts
+++ b/web/src/features/events/server/eventsService.ts
@@ -1,7 +1,7 @@
import { type z } from "zod";
import {
- AGGREGATABLE_SCORE_TYPES,
type FilterCondition,
+ LISTABLE_SCORE_TYPES,
filterAndValidateDbScoreList,
} from "@langfuse/shared";
import {
@@ -128,13 +128,13 @@ export async function getEventList(params: GetObservationsListParams) {
const validatedScores = filterAndValidateDbScoreList({
scores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
includeHasMetadata: true,
onParseError: traceException,
});
const validatedTraceScores = filterAndValidateDbScoreList({
scores: traceScores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
includeHasMetadata: true,
onParseError: traceException,
});
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index 8de20c02d7..0ab02b9570 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -13,7 +13,7 @@ import {
shouldSkipObservationsFinal,
} from "@langfuse/shared/src/server";
import {
- AGGREGATABLE_SCORE_TYPES,
+ LISTABLE_SCORE_TYPES,
type OrderByState,
tracesTableCols,
} from "@langfuse/shared";
@@ -376,7 +376,7 @@ async function buildTracesBaseQuery(
...appliedEnvironmentFilter.params,
...appliedFilter.params,
projectId: props.projectId,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
...(props.limit !== undefined ? { limit: props.limit } : {}),
...(props.page !== undefined
? { offset: (props.page - 1) * props.limit }
diff --git a/web/src/features/public-api/types/score-configs.ts b/web/src/features/public-api/types/score-configs.ts
index dd9e391d0a..f4940c3bcc 100644
--- a/web/src/features/public-api/types/score-configs.ts
+++ b/web/src/features/public-api/types/score-configs.ts
@@ -1,6 +1,7 @@
import {
BooleanConfigFields,
CategoricalConfigFields,
+ TextConfigFields,
jsonSchema,
NumericConfigFields,
paginationMetaResponseZod,
@@ -53,6 +54,10 @@ const APIScoreConfig = z
...ScoreConfigBase.shape,
...BooleanConfigFields.shape,
}),
+ z.object({
+ ...ScoreConfigBase.shape,
+ ...TextConfigFields.shape,
+ }),
])
.superRefine(validateNumericRangeFields);
diff --git a/web/src/features/score-configs/components/UpsertScoreConfigDialog.tsx b/web/src/features/score-configs/components/UpsertScoreConfigDialog.tsx
index 0a81853e73..24eb3e4951 100644
--- a/web/src/features/score-configs/components/UpsertScoreConfigDialog.tsx
+++ b/web/src/features/score-configs/components/UpsertScoreConfigDialog.tsx
@@ -34,6 +34,7 @@ import { Textarea } from "@/src/components/ui/textarea";
import {
isBooleanDataType,
isCategoricalDataType,
+ isTextDataType,
isNumericDataType,
} from "@/src/features/scores/lib/helpers";
import DocPopup from "@/src/components/layouts/doc-popup";
@@ -192,16 +193,19 @@ export function UpsertScoreConfigDialog({
disabled={!!id}
defaultValue={field.value}
onValueChange={(value) => {
- field.onChange(value as ScoreConfigDataType);
+ const dt = value as ScoreConfigDataType;
+ field.onChange(dt);
form.clearErrors();
- if (isNumericDataType(value as ScoreConfigDataType)) {
+ if (isNumericDataType(dt)) {
form.setValue("categories", undefined);
+ } else if (isTextDataType(dt)) {
+ form.setValue("categories", undefined);
+ form.setValue("minValue", undefined);
+ form.setValue("maxValue", undefined);
} else {
form.setValue("minValue", undefined);
form.setValue("maxValue", undefined);
- if (
- isBooleanDataType(value as ScoreConfigDataType)
- ) {
+ if (isBooleanDataType(dt)) {
replace([
{ label: "True", value: 1 },
{ label: "False", value: 0 },
@@ -282,7 +286,7 @@ export function UpsertScoreConfigDialog({
)}
/>
</>
- ) : (
+ ) : isTextDataType(form.getValues("dataType")) ? null : (
<div className="grid grid-flow-row gap-2">
<FormField
control={form.control}
diff --git a/web/src/features/score-configs/lib/upsertFormTypes.ts b/web/src/features/score-configs/lib/upsertFormTypes.ts
index f64c9b08a5..0f9b9a396f 100644
--- a/web/src/features/score-configs/lib/upsertFormTypes.ts
+++ b/web/src/features/score-configs/lib/upsertFormTypes.ts
@@ -4,7 +4,7 @@ import { z } from "zod";
export const createConfigSchema = z.object({
name: z.string().min(1).max(35),
description: z.string().optional(),
- dataType: z.enum(["CATEGORICAL", "NUMERIC", "BOOLEAN"]),
+ dataType: z.enum(["CATEGORICAL", "NUMERIC", "BOOLEAN", "TEXT"]),
minValue: z.coerce.number().optional(),
maxValue: z.coerce.number().optional(),
categories: z.array(ScoreConfigCategory).optional(),
diff --git a/web/src/features/score-configs/lib/validateScoreConfigUpsertFormInput.ts b/web/src/features/score-configs/lib/validateScoreConfigUpsertFormInput.ts
index 8bcca51e26..d749720069 100644
--- a/web/src/features/score-configs/lib/validateScoreConfigUpsertFormInput.ts
+++ b/web/src/features/score-configs/lib/validateScoreConfigUpsertFormInput.ts
@@ -2,6 +2,7 @@ import {
NumericConfigFields,
CategoricalConfigFields,
BooleanConfigFields,
+ TextConfigFields,
validateNumericRangeFields,
} from "@langfuse/shared";
import { z } from "zod";
@@ -19,6 +20,7 @@ const ScoreConfigValidationSchema = ScoreConfigBaseSchema.and(
NumericConfigFields,
CategoricalConfigFields,
BooleanConfigFields,
+ TextConfigFields,
])
.superRefine(validateNumericRangeFields),
);
diff --git a/web/src/features/scores/components/AnnotationForm.tsx b/web/src/features/scores/components/AnnotationForm.tsx
index 597b4c5e28..e4e1f4f9bc 100644
--- a/web/src/features/scores/components/AnnotationForm.tsx
+++ b/web/src/features/scores/components/AnnotationForm.tsx
@@ -25,6 +25,7 @@ import {
type ScoreConfigCategoryDomain,
type UpdateAnnotationScoreData,
type CreateAnnotationScoreData,
+ TEXT_SCORE_MAX_LENGTH,
} from "@langfuse/shared";
import { Input } from "@/src/components/ui/input";
import {
@@ -39,6 +40,7 @@ import { HoverCardContent } from "@radix-ui/react-hover-card";
import { HoverCard, HoverCardTrigger } from "@/src/components/ui/hover-card";
import {
formatAnnotateDescription,
+ isTextDataType,
isNumericDataType,
isScoreUnsaved,
} from "@/src/features/scores/lib/helpers";
@@ -487,6 +489,21 @@ function InnerAnnotationForm<Target extends ScoreTarget>({
handleUpsert(index, numericCategoryValue, stringValue);
};
+ const handleTextUpsert = (index: number) => {
+ const field = controlledFields[index];
+ const config = configs.find((c) => c.id === field.configId);
+
+ if (!config || !field) return;
+ if (!field.stringValue) {
+ if (field.id) {
+ handleDeleteScore(index);
+ }
+ return;
+ }
+
+ handleUpsert(index, 0, field.stringValue);
+ };
+
const rollbackCommentError = (
index: number,
field: (typeof controlledFields)[number],
@@ -676,7 +693,28 @@ function InnerAnnotationForm<Target extends ScoreTarget>({
</Popover>
</div>
<div className="grid grid-cols-[11fr_1fr] items-center py-1">
- {isNumericDataType(score.dataType) ? (
+ {isTextDataType(score.dataType) ? (
+ <FormField
+ control={form.control}
+ name={`scoreData.${index}.stringValue`}
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Textarea
+ {...field}
+ value={field.value ?? ""}
+ maxLength={TEXT_SCORE_MAX_LENGTH}
+ className="text-xs"
+ disabled={isInputDisabled(config)}
+ placeholder="Enter free form text..."
+ onBlur={() => handleTextUpsert(index)}
+ />
+ </FormControl>
+ <FormMessage className="text-xs" />
+ </FormItem>
+ )}
+ />
+ ) : isNumericDataType(score.dataType) ? (
<FormField
control={form.control}
name={`scoreData.${index}.value`}
diff --git a/web/src/features/scores/lib/aggregateScores.ts b/web/src/features/scores/lib/aggregateScores.ts
index 7714335a28..a9f354e3ec 100644
--- a/web/src/features/scores/lib/aggregateScores.ts
+++ b/web/src/features/scores/lib/aggregateScores.ts
@@ -4,7 +4,9 @@ import {
type ScoreSimplified,
type ScoreSourceType,
type ScoreDomain,
- type AggregatableScoreDataType,
+ type ScoreDataTypeType,
+ type ListableScore,
+ type ListableScoreDataType,
} from "@langfuse/shared";
/**
@@ -22,7 +24,7 @@ export const composeAggregateScoreKey = ({
}: {
name: string;
source: ScoreSourceType;
- dataType: AggregatableScoreDataType;
+ dataType: ScoreDataTypeType;
keyPrefix?: string;
}): string => {
const formattedName = normalizeScoreName(name);
@@ -34,13 +36,13 @@ export const decomposeAggregateScoreKey = (
): {
name: string;
source: ScoreSourceType;
- dataType: AggregatableScoreDataType;
+ dataType: ScoreDataTypeType;
} => {
const [name, source, dataType] = key.split("-");
return {
name,
source: source as ScoreSourceType,
- dataType: dataType as AggregatableScoreDataType,
+ dataType: dataType as ScoreDataTypeType,
};
};
@@ -51,7 +53,7 @@ export const getScoreLabelFromKey = (key: string): string => {
export type ScoreToAggregate =
| (Omit<ScoreDomain, "dataType"> & {
- dataType: AggregatableScoreDataType;
+ dataType: ListableScore["dataType"];
hasMetadata?: boolean;
})
| (ScoreSimplified & {
@@ -64,9 +66,9 @@ export type ScoreToAggregate =
* aggregation logic (value counting vs numeric averaging).
*/
export const resolveAggregateType = (
- dataType: AggregatableScoreDataType,
+ dataType: ListableScoreDataType,
): "NUMERIC" | "CATEGORICAL" => {
- return dataType === "BOOLEAN" ? "CATEGORICAL" : dataType;
+ return dataType === "NUMERIC" ? "NUMERIC" : "CATEGORICAL";
};
export const aggregateScores = <T extends ScoreToAggregate>(
diff --git a/web/src/features/scores/lib/helpers.ts b/web/src/features/scores/lib/helpers.ts
index fdb68fb0f8..3f04b8ecb1 100644
--- a/web/src/features/scores/lib/helpers.ts
+++ b/web/src/features/scores/lib/helpers.ts
@@ -16,6 +16,9 @@ export const isCategoricalDataType = (dataType: ScoreDataTypeType) =>
export const isBooleanDataType = (dataType: ScoreDataTypeType) =>
dataType === ScoreDataTypeEnum.BOOLEAN;
+export const isTextDataType = (dataType: ScoreDataTypeType) =>
+ dataType === ScoreDataTypeEnum.TEXT;
+
export const isScoreUnsaved = (scoreId?: string | null): boolean => !scoreId;
export const toOrderedScoresList = (list: ScoreData[]): ScoreData[] =>
diff --git a/web/src/features/scores/lib/scoreColumns.ts b/web/src/features/scores/lib/scoreColumns.ts
index 2cad6bbd3c..e5fdac3f7b 100644
--- a/web/src/features/scores/lib/scoreColumns.ts
+++ b/web/src/features/scores/lib/scoreColumns.ts
@@ -169,6 +169,8 @@ export const getScoreDataTypeIcon = (dataType: ScoreDataTypeType): string => {
return "â’·";
case "CORRECTION":
return "";
+ case "TEXT":
+ return "Aa";
}
};
diff --git a/web/src/features/scores/lib/transformScores.ts b/web/src/features/scores/lib/transformScores.ts
index 92b058a02a..d0f5c64af3 100644
--- a/web/src/features/scores/lib/transformScores.ts
+++ b/web/src/features/scores/lib/transformScores.ts
@@ -109,12 +109,18 @@ function transformAggregates(
const scores: AnnotationScore[] = [];
Object.entries(mergedAggregates).forEach(([key, aggregate]) => {
- const { name, source, dataType } = decomposeAggregateScoreKey(key);
+ const {
+ name,
+ source,
+ dataType: rawDataType,
+ } = decomposeAggregateScoreKey(key);
// Only ANNOTATION source can be edited, and must have single ID
// Multi-value aggregates (no id) are child observation scores - skip them
if (source !== "ANNOTATION" || !aggregate.id) return;
+ const dataType = rawDataType as AnnotationScoreDataType;
+
const config = configs.find(
(c) => normalizeScoreName(c.name) === name && c.dataType === dataType,
);
diff --git a/web/src/features/scores/types.ts b/web/src/features/scores/types.ts
index cd2aaa21bb..d97d55430b 100644
--- a/web/src/features/scores/types.ts
+++ b/web/src/features/scores/types.ts
@@ -8,7 +8,6 @@ import {
type ScoreAggregate,
type ScoreConfigDomain,
type ScoreDomain,
- type AggregatableScoreDataType,
ScoreConfigDataType,
} from "@langfuse/shared";
import { type z } from "zod";
@@ -106,7 +105,7 @@ export type ScoreColumn = {
key: string;
name: string;
source: ScoreSourceType;
- dataType: AggregatableScoreDataType;
+ dataType: AnnotationScoreDataType;
};
export type ScoreConfigSelection =
diff --git a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
index 621558a073..077e68a9f1 100644
--- a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
+++ b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
@@ -1,8 +1,8 @@
import { env } from "@/src/env.mjs";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
import {
- AGGREGATABLE_SCORE_TYPES,
filterAndValidateDbScoreList,
+ LISTABLE_SCORE_TYPES,
} from "@langfuse/shared";
import {
getObservationsTableWithModelData,
@@ -43,7 +43,7 @@ export async function getAllGenerations({
const validatedScores = filterAndValidateDbScoreList({
scores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
includeHasMetadata: true,
onParseError: traceException,
});
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index 8a8023ee75..82a9ac18a9 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -19,7 +19,7 @@ import {
timeFilter,
type SessionOptions,
type ScoreDomain,
- AGGREGATABLE_SCORE_TYPES,
+ LISTABLE_SCORE_TYPES,
} from "@langfuse/shared";
import { Prisma } from "@langfuse/shared/src/db";
import { TRPCError } from "@trpc/server";
@@ -127,7 +127,7 @@ const handleGetSessionById = async (input: {
const validatedScores = filterAndValidateDbScoreList({
scores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
onParseError: traceException,
});
@@ -405,7 +405,7 @@ export const sessionRouter = createTRPCRouter({
const validatedScores = filterAndValidateDbScoreList({
scores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
onParseError: traceException,
});
@@ -474,7 +474,7 @@ export const sessionRouter = createTRPCRouter({
const validatedScores = filterAndValidateDbScoreList({
scores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
onParseError: traceException,
});
@@ -657,7 +657,7 @@ export const sessionRouter = createTRPCRouter({
const validatedScores: ScoreDomain[] = filterAndValidateDbScoreList({
scores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
onParseError: traceException,
});
@@ -701,7 +701,7 @@ export const sessionRouter = createTRPCRouter({
const validatedScores: ScoreDomain[] = filterAndValidateDbScoreList({
scores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
onParseError: traceException,
});
@@ -747,7 +747,7 @@ export const sessionRouter = createTRPCRouter({
const validatedScores = filterAndValidateDbScoreList({
scores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
onParseError: traceException,
});
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index 67fb5e9b48..b4866c57d7 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -22,8 +22,9 @@ import {
type Observation,
TracingSearchType,
type ScoreDomain,
- AGGREGATABLE_SCORE_TYPES,
+ ScoreDataTypeArray,
ScoreDataTypeEnum,
+ LISTABLE_SCORE_TYPES,
} from "@langfuse/shared";
import {
traceException,
@@ -244,7 +245,7 @@ export const traceRouter = createTRPCRouter({
const validatedScores = filterAndValidateDbScoreList({
scores: traceScores,
- dataTypes: AGGREGATABLE_SCORE_TYPES,
+ dataTypes: LISTABLE_SCORE_TYPES,
includeHasMetadata: true,
onParseError: traceException,
});
@@ -379,7 +380,7 @@ export const traceRouter = createTRPCRouter({
const validatedScores = filterAndValidateDbScoreList({
scores: traceScores,
- dataTypes: [...AGGREGATABLE_SCORE_TYPES, ScoreDataTypeEnum.CORRECTION],
+ dataTypes: [...ScoreDataTypeArray],
onParseError: traceException,
});
diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.ts
index 75af6b85fb..f9364339a9 100644
--- a/worker/src/features/database-read-stream/event-stream.ts
+++ b/worker/src/features/database-read-stream/event-stream.ts
@@ -9,7 +9,6 @@
import {
FilterCondition,
- ScoreDataTypeEnum,
type ScoreDataTypeType,
TimeFilter,
TracingSearchType,
@@ -198,7 +197,7 @@ export const getEventsStream = async (props: {
}[]
| undefined;
score_categories: string[] | undefined;
- score_categories_tuples: [string, string | null][] | undefined;
+ score_categories_tuples: [string, string | null, string][] | undefined;
};
const asyncGenerator = queryClickhouseStream<EventRow>({
@@ -228,10 +227,10 @@ export const getEventsStream = async (props: {
// Process categorical scores (tuples from ClickHouse)
const categoricalScores = (bufferedRow.score_categories_tuples ?? []).map(
- (cat) => ({
+ (cat: [string, string | null, string]) => ({
name: cat[0],
value: null,
- dataType: ScoreDataTypeEnum.CATEGORICAL,
+ dataType: cat[2],
stringValue: cat[1],
}),
);
diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.ts
index 8d1d7883e8..300cf51a70 100644
--- a/worker/src/features/database-read-stream/observation-stream.ts
+++ b/worker/src/features/database-read-stream/observation-stream.ts
@@ -1,7 +1,6 @@
import {
BatchExportFileFormat,
FilterCondition,
- ScoreDataTypeEnum,
type ScoreDataTypeType,
TimeFilter,
TracingSearchType,
@@ -142,12 +141,12 @@ export const getObservationStream = async (props: {
-- concat encoding for hasAny filter compatibility
groupArrayIf(
concat(name, ':', string_value),
- data_type = 'CATEGORICAL' AND notEmpty(string_value)
+ data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)
) AS score_categories,
-- tuple encoding for accurate output parsing (names may contain colons)
groupArrayIf(
- tuple(name, string_value),
- data_type = 'CATEGORICAL' AND notEmpty(string_value)
+ tuple(name, string_value, data_type),
+ data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)
) AS score_categories_tuples
FROM (
SELECT
@@ -235,7 +234,7 @@ export const getObservationStream = async (props: {
}[]
| undefined;
score_categories: string[] | undefined;
- score_categories_tuples: [string, string | null][] | undefined;
+ score_categories_tuples: [string, string | null, string][] | undefined;
} & {
traceName: string;
traceTags: string[];
@@ -277,7 +276,7 @@ export const getObservationStream = async (props: {
}[]
| undefined;
score_categories: string[] | undefined;
- score_categories_tuples: [string, string | null][] | undefined;
+ score_categories_tuples: [string, string | null, string][] | undefined;
} & {
traceName: string;
traceTags: string[];
@@ -306,7 +305,7 @@ export const getObservationStream = async (props: {
(cat) => ({
name: cat[0],
value: null,
- dataType: ScoreDataTypeEnum.CATEGORICAL,
+ dataType: cat[2],
stringValue: cat[1],
}),
);
diff --git a/worker/src/features/database-read-stream/trace-stream.ts b/worker/src/features/database-read-stream/trace-stream.ts
index e69a02e24a..2e104c4d1b 100644
--- a/worker/src/features/database-read-stream/trace-stream.ts
+++ b/worker/src/features/database-read-stream/trace-stream.ts
@@ -1,6 +1,5 @@
import {
FilterCondition,
- ScoreDataTypeEnum,
type ScoreDataTypeType,
TracingSearchType,
tracesTableCols,
@@ -126,12 +125,12 @@ export const getTraceStream = async (props: {
-- concat encoding for hasAny filter compatibility
groupArrayIf(
concat(name, ':', string_value),
- data_type = 'CATEGORICAL' AND notEmpty(string_value)
+ data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)
) AS score_categories,
-- tuple encoding for accurate output parsing (names may contain colons)
groupArrayIf(
- tuple(name, string_value),
- data_type = 'CATEGORICAL' AND notEmpty(string_value)
+ tuple(name, string_value, data_type),
+ data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)
) AS score_categories_tuples
FROM (
SELECT
@@ -206,7 +205,7 @@ export const getTraceStream = async (props: {
}[]
| undefined;
score_categories: string[] | undefined;
- score_categories_tuples: [string, string | null][] | undefined;
+ score_categories_tuples: [string, string | null, string][] | undefined;
}>({
query,
params: {
@@ -238,12 +237,12 @@ export const getTraceStream = async (props: {
stringValue: score[3],
}));
- // Process categorical scores (tuples from ClickHouse)
+ // Process categorical / text scores (tuples from ClickHouse)
const categoricalScores = (bufferedRow.score_categories_tuples ?? []).map(
- (cat: [string, string | null]) => ({
+ (cat: [string, string | null, string]) => ({
name: cat[0],
value: null,
- dataType: ScoreDataTypeEnum.CATEGORICAL,
+ dataType: cat[2],
stringValue: cat[1],
}),
);