Skip to content

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

chore: add long string value column to scores table (#11233)

marliessophiea9621b2673c9
diff --git a/fern/apis/client/definition/score.yml b/fern/apis/client/definition/score.yml
index cb7c41ae7a..4dee0501cc 100644
--- a/fern/apis/client/definition/score.yml
+++ b/fern/apis/client/definition/score.yml
@@ -18,7 +18,9 @@ types:
sessionId: optional<string>
observationId: optional<string>
datasetRunId: optional<string>
- name: string
+ name:
+ type: string
+ docs: The name of the score. Always overrides "output" for correction scores.
value:
type: CreateScoreValue
docs: The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false)
@@ -81,10 +83,11 @@ types:
- NUMERIC
- CATEGORICAL
- BOOLEAN
+ - CORRECTION
CreateScoreValue:
discriminated: false
union:
- double
- string
- docs: The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores
+ docs: The value of the score. Must be passed as string for categorical scores, and numeric for boolean and numeric scores. For corrections pass value as string and set data type to CORRECTION
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index d91bfcacaa..2fdcdef75b 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -222,7 +222,7 @@ types:
createdAt: datetime
updatedAt: datetime
projectId: string
- dataType: ScoreDataType
+ dataType: ScoreConfigDataType
isArchived:
type: boolean
docs: Whether the score config is archived. Defaults to false
@@ -730,11 +730,18 @@ types:
- ANNOTATION
- API
- EVAL
+ ScoreConfigDataType:
+ enum:
+ - NUMERIC
+ - BOOLEAN
+ - CATEGORICAL
+
ScoreDataType:
enum:
- NUMERIC
- BOOLEAN
- CATEGORICAL
+ - CORRECTION
errors:
Error:
diff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.yml
index ac8deffe89..c1b31b172e 100644
--- a/fern/apis/server/definition/ingestion.yml
+++ b/fern/apis/server/definition/ingestion.yml
@@ -278,7 +278,9 @@ types:
sessionId: optional<string>
observationId: optional<string>
datasetRunId: optional<string>
- name: string
+ name:
+ type: string
+ docs: The name of the score. Always overrides "output" for correction scores.
environment: optional<string>
queueId:
type: optional<string>
diff --git a/fern/apis/server/definition/score-configs.yml b/fern/apis/server/definition/score-configs.yml
index bfa31ecf58..25a3975585 100644
--- a/fern/apis/server/definition/score-configs.yml
+++ b/fern/apis/server/definition/score-configs.yml
@@ -55,7 +55,7 @@ types:
CreateScoreConfigRequest:
properties:
name: string
- dataType: commons.ScoreDataType
+ dataType: commons.ScoreConfigDataType
categories:
type: optional<list<commons.ConfigCategory>>
docs: Configure custom categories for categorical scores. Pass a list of objects with `label` and `value` properties. Categories are autogenerated for boolean configs and cannot be passed
diff --git a/packages/shared/clickhouse/migrations/clustered/0034_add_long_string_value_to_scores.down.sql b/packages/shared/clickhouse/migrations/clustered/0034_add_long_string_value_to_scores.down.sql
new file mode 100644
index 0000000000..c9f9555be8
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/clustered/0034_add_long_string_value_to_scores.down.sql
@@ -0,0 +1 @@
+ALTER TABLE scores ON CLUSTER default DROP COLUMN IF EXISTS long_string_value;
diff --git a/packages/shared/clickhouse/migrations/clustered/0034_add_long_string_value_to_scores.up.sql b/packages/shared/clickhouse/migrations/clustered/0034_add_long_string_value_to_scores.up.sql
new file mode 100644
index 0000000000..1e54324ca8
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/clustered/0034_add_long_string_value_to_scores.up.sql
@@ -0,0 +1 @@
+ALTER TABLE scores ON CLUSTER default ADD COLUMN IF NOT EXISTS long_string_value String CODEC(ZSTD(3));
diff --git a/packages/shared/clickhouse/migrations/unclustered/0034_add_long_string_value_to_scores.down.sql b/packages/shared/clickhouse/migrations/unclustered/0034_add_long_string_value_to_scores.down.sql
new file mode 100644
index 0000000000..b10e392480
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/unclustered/0034_add_long_string_value_to_scores.down.sql
@@ -0,0 +1 @@
+ALTER TABLE scores DROP COLUMN IF EXISTS long_string_value;
diff --git a/packages/shared/clickhouse/migrations/unclustered/0034_add_long_string_value_to_scores.up.sql b/packages/shared/clickhouse/migrations/unclustered/0034_add_long_string_value_to_scores.up.sql
new file mode 100644
index 0000000000..7dfe2da5cf
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/unclustered/0034_add_long_string_value_to_scores.up.sql
@@ -0,0 +1 @@
+ALTER TABLE scores ADD COLUMN IF NOT EXISTS long_string_value String CODEC(ZSTD(3));
diff --git a/packages/shared/scripts/seeder/utils/data-generators.ts b/packages/shared/scripts/seeder/utils/data-generators.ts
index e40cfa90ca..cc13821d94 100644
--- a/packages/shared/scripts/seeder/utils/data-generators.ts
+++ b/packages/shared/scripts/seeder/utils/data-generators.ts
@@ -1206,6 +1206,7 @@ export class DataGenerator {
config_id: null,
data_type: "NUMERIC",
string_value: null,
+ long_string_value: "",
queue_id: null,
created_at: baseTs,
updated_at: baseTs,
@@ -1225,6 +1226,7 @@ export class DataGenerator {
environment: "default",
name: "safe",
value: safeVal,
+ long_string_value: "",
source: "API",
comment: "Content safety",
metadata: {},
@@ -1252,6 +1254,7 @@ export class DataGenerator {
observation_id: null,
environment: "default",
name: "resolved",
+ long_string_value: "",
value: 1,
source: "API",
comment: "Conversation resolved",
diff --git a/packages/shared/src/domain/scores.ts b/packages/shared/src/domain/scores.ts
index bfac33caf3..528a1511cc 100644
--- a/packages/shared/src/domain/scores.ts
+++ b/packages/shared/src/domain/scores.ts
@@ -10,15 +10,19 @@ export const ScoreSourceEnum = {
export const ScoreSourceDomain = z.enum(ScoreSourceArray);
export type ScoreSourceType = z.infer<typeof ScoreSourceDomain>;
+export const CORRECTION_NAME = "output" as const;
+
export const ScoreDataTypeArray = [
"NUMERIC",
"CATEGORICAL",
"BOOLEAN",
+ "CORRECTION",
] as const;
export const ScoreDataTypeEnum = {
NUMERIC: "NUMERIC",
CATEGORICAL: "CATEGORICAL",
BOOLEAN: "BOOLEAN",
+ CORRECTION: "CORRECTION",
} as const;
export const ScoreDataTypeDomain = z.enum(ScoreDataTypeArray);
export type ScoreDataTypeType = z.infer<typeof ScoreDataTypeDomain>;
@@ -38,6 +42,11 @@ export const BooleanData = z.object({
dataType: z.literal("BOOLEAN"),
});
+const CorrectionData = z.object({
+ stringValue: z.null(),
+ dataType: z.literal("CORRECTION"),
+});
+
// Only used for backwards compatibility with old score API schemas
export const ScoreSchemaExclReferencesAndDates = z.object({
// Core identifiers
@@ -70,11 +79,43 @@ const ScoreFoundationSchema = ScoreSchemaExclReferencesAndDates.and(
sessionId: z.string().nullable(),
datasetRunId: z.string().nullable(),
observationId: z.string().nullable(),
+ longStringValue: z.string().default(""),
}),
);
export const ScoreSchema = ScoreFoundationSchema.and(
- z.discriminatedUnion("dataType", [NumericData, CategoricalData, BooleanData]),
+ z.discriminatedUnion("dataType", [
+ NumericData,
+ CategoricalData,
+ BooleanData,
+ CorrectionData,
+ ]),
);
export type ScoreDomain = z.infer<typeof ScoreSchema>;
+
+export type ScoreByDataType<T extends ScoreDataTypeType> = ScoreDomain & {
+ dataType: T;
+};
+
+export type ScoresByDataTypes<T extends readonly ScoreDataTypeType[]> =
+ T extends readonly (infer U)[]
+ ? U extends ScoreDataTypeType
+ ? ScoreByDataType<U>
+ : never
+ : never;
+
+// Aggregatable score types - used in most read queries to exclude CORRECTION scores
+export const AGGREGATABLE_SCORE_TYPES = [
+ "NUMERIC",
+ "BOOLEAN",
+ "CATEGORICAL",
+] as const satisfies readonly ScoreDataTypeType[];
+
+export type AggregatableScoreDataType =
+ (typeof AGGREGATABLE_SCORE_TYPES)[number];
+
+// Type helper for functions that return only aggregatable scores
+export type AggregatableScore = ScoresByDataTypes<
+ typeof AGGREGATABLE_SCORE_TYPES
+>;
diff --git a/packages/shared/src/features/scores/interfaces/api/shared.ts b/packages/shared/src/features/scores/interfaces/api/shared.ts
index 088da3959d..bffdaa2f15 100644
--- a/packages/shared/src/features/scores/interfaces/api/shared.ts
+++ b/packages/shared/src/features/scores/interfaces/api/shared.ts
@@ -69,6 +69,11 @@ export const PostScoresBody = applyScoreValidation(
dataType: z.literal("BOOLEAN"),
configId: z.string().nullish(),
}),
+ z.object({
+ value: z.string(), // Corrected output text
+ dataType: z.literal("CORRECTION"),
+ configId: z.undefined().nullish(), // Cannot have config
+ }),
z.object({
value: z.union([z.string(), z.number()]),
dataType: z.undefined(),
diff --git a/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts b/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts
index 5d29d0d724..3c7d057d68 100644
--- a/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts
+++ b/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts
@@ -6,6 +6,11 @@ import {
} from "../../../../../domain";
import z from "zod/v4";
+const CorrectionData = z.object({
+ stringValue: z.string(),
+ dataType: z.literal("CORRECTION"),
+});
+
/**
* Foundation schema for scores API v2 i.e. trace, observation AND session scores
*
@@ -25,7 +30,12 @@ const ScoreFoundationSchemaV2 = ScoreSchemaExclReferencesAndDates.extend({
});
export const APIScoreSchemaV2 = ScoreFoundationSchemaV2.and(
- z.discriminatedUnion("dataType", [NumericData, CategoricalData, BooleanData]),
+ z.discriminatedUnion("dataType", [
+ NumericData,
+ CategoricalData,
+ BooleanData,
+ CorrectionData,
+ ]),
);
export type APIScoreV2 = z.infer<typeof APIScoreSchemaV2>;
diff --git a/packages/shared/src/features/scores/interfaces/application/validation.ts b/packages/shared/src/features/scores/interfaces/application/validation.ts
index 5363381116..698ec29594 100644
--- a/packages/shared/src/features/scores/interfaces/application/validation.ts
+++ b/packages/shared/src/features/scores/interfaces/application/validation.ts
@@ -1,8 +1,16 @@
import z from "zod/v4";
import { APIScoreSchemaV1, APIScoreV1 } from "../api/v1/schemas";
-import { ScoreDomain, ScoreSchema } from "../../../../domain";
+import {
+ ScoreDomain,
+ ScoreSchema,
+ ScoreDataTypeType,
+ ScoresByDataTypes,
+} from "../../../../domain";
-type ValidatedScore<IncludeHasMetadata extends boolean> = ScoreDomain & {
+type ValidatedScore<
+ IncludeHasMetadata extends boolean,
+ DataTypes extends readonly ScoreDataTypeType[],
+> = ScoresByDataTypes<DataTypes> & {
hasMetadata: IncludeHasMetadata extends true ? boolean : never;
};
@@ -21,35 +29,50 @@ export const validateDbScore = (score: unknown): ScoreDomain =>
/**
* Use this function when pulling a list of scores from the database before using in the application to ensure type safety.
* All scores are expected to pass the validation. If a score fails validation, it will be logged to Otel.
- * @param scores
- * @returns list of validated scores
+ * This function filters scores by the specified data types and validates them.
+ * @param scores - List of scores to filter and validate
+ * @param dataTypes - Array of data types to filter by (required)
+ * @param includeHasMetadata - Whether to include hasMetadata field
+ * @param onParseError - Optional callback for parse errors
+ * @returns list of validated and filtered scores
*/
export const filterAndValidateDbScoreList = <
IncludeHasMetadata extends boolean,
+ DataTypes extends readonly ScoreDataTypeType[],
>({
scores,
+ dataTypes,
includeHasMetadata = false as IncludeHasMetadata,
onParseError,
}: {
scores: InputScore[];
+ dataTypes: DataTypes;
includeHasMetadata?: IncludeHasMetadata;
// eslint-disable-next-line no-unused-vars
onParseError?: (error: z.ZodError) => void;
-}): ValidatedScore<IncludeHasMetadata>[] => {
- return scores.reduce((acc, ts) => {
- const result = ScoreSchema.safeParse(ts);
- if (result.success) {
- const score = { ...result.data };
- if (includeHasMetadata) {
- Object.assign(score, { hasMetadata: ts.hasMetadata ?? false });
+}): ValidatedScore<IncludeHasMetadata, DataTypes>[] => {
+ return scores.reduce(
+ (acc, ts) => {
+ // Filter by dataType first
+ if (!dataTypes.includes(ts.dataType)) {
+ return acc;
}
- acc.push(score as ValidatedScore<IncludeHasMetadata>);
- } else {
- console.error("Score parsing error: ", result.error);
- onParseError?.(result.error);
- }
- return acc;
- }, [] as ValidatedScore<IncludeHasMetadata>[]);
+
+ const result = ScoreSchema.safeParse(ts);
+ if (result.success) {
+ const score = { ...result.data };
+ if (includeHasMetadata) {
+ Object.assign(score, { hasMetadata: ts.hasMetadata ?? false });
+ }
+ acc.push(score as ValidatedScore<IncludeHasMetadata, DataTypes>);
+ } else {
+ console.error("Score parsing error: ", result.error);
+ onParseError?.(result.error);
+ }
+ return acc;
+ },
+ [] as ValidatedScore<IncludeHasMetadata, DataTypes>[],
+ );
};
type ValidatedAPITraceScore<IncludeHasMetadata extends boolean> = APIScoreV1 & {
diff --git a/packages/shared/src/features/scores/interfaces/ingestion/validation.ts b/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
index 6b785b9bb7..316b08e7d2 100644
--- a/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
+++ b/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
@@ -18,6 +18,12 @@ export const ScoreBodyWithoutConfig = applyScoreValidation(
dataType: z.literal("CATEGORICAL"),
}),
),
+ PostScoreBodyFoundationSchema.merge(
+ z.object({
+ value: z.string(),
+ dataType: z.literal("CORRECTION"),
+ }),
+ ),
PostScoreBodyFoundationSchema.merge(
z.object({
value: z.number().refine((val) => val === 0 || val === 1, {
diff --git a/packages/shared/src/features/scores/interfaces/ui/types.ts b/packages/shared/src/features/scores/interfaces/ui/types.ts
index 6737636108..12798e15a0 100644
--- a/packages/shared/src/features/scores/interfaces/ui/types.ts
+++ b/packages/shared/src/features/scores/interfaces/ui/types.ts
@@ -1,6 +1,6 @@
import {
+ AggregatableScoreDataType,
MetadataDomain,
- ScoreDataTypeType,
ScoreSourceType,
} from "../../../../domain";
@@ -30,7 +30,7 @@ export type ScoreAggregate = Record<string, AggregatedScoreData>;
export type ScoreSimplified = {
id: string;
name: string;
- dataType: ScoreDataTypeType;
+ dataType: AggregatableScoreDataType;
source: ScoreSourceType;
value?: number | null;
comment?: string | null;
diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.ts
index 6d12f3c4e8..86a55fbeba 100644
--- a/packages/shared/src/server/ingestion/types.ts
+++ b/packages/shared/src/server/ingestion/types.ts
@@ -534,6 +534,13 @@ const createAllIngestionSchemas = ({
configId: z.string().nullish(),
}),
),
+ BaseScoreBody.merge(
+ z.object({
+ value: z.string(),
+ dataType: z.literal("CORRECTION"),
+ configId: z.undefined().nullish(), // Cannot have config
+ }),
+ ),
BaseScoreBody.merge(
z.object({
value: z.union([z.string(), z.number()]),
diff --git a/packages/shared/src/server/ingestion/validateAndInflateScore.ts b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
index 1d0e2111ec..f5634c10e4 100644
--- a/packages/shared/src/server/ingestion/validateAndInflateScore.ts
+++ b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
@@ -1,10 +1,11 @@
import {
ScoreBodyWithoutConfig,
ScoreConfigDomain,
- ScoreDataTypeEnum,
type ScoreDataTypeType,
type ScoreDomain,
ScorePropsAgainstConfig,
+ ScoreDataTypeEnum,
+ CORRECTION_NAME,
} from "../../../src";
import { prisma } from "../../db";
import { InvalidRequestError, LangfuseNotFoundError } from "../../errors";
@@ -93,6 +94,7 @@ function inflateScoreBody(
const relevantDataType = config?.dataType ?? body.dataType;
const scoreProps = {
...body,
+ longStringValue: "",
source: body.source ?? "API",
id: scoreId,
projectId,
@@ -116,6 +118,29 @@ function inflateScoreBody(
};
}
+ if (relevantDataType && relevantDataType === ScoreDataTypeEnum.CORRECTION) {
+ // CORRECTION scores can only be associated with traces or observations
+ if (body.sessionId) {
+ throw new InvalidRequestError(
+ "CORRECTION scores cannot be associated with sessions. Please associate with a trace or observation instead.",
+ );
+ }
+ if (body.datasetRunId) {
+ throw new InvalidRequestError(
+ "CORRECTION scores cannot be associated with dataset runs. Please associate with a trace or observation instead.",
+ );
+ }
+
+ return {
+ ...scoreProps,
+ value: 0,
+ name: CORRECTION_NAME,
+ longStringValue: body.value,
+ stringValue: null,
+ dataType: ScoreDataTypeEnum.CORRECTION,
+ };
+ }
+
return {
...scoreProps,
value: config ? mapStringValueToNumericValue(config, body.value) : 0,
@@ -149,6 +174,8 @@ function resolveScoreValueAnnotation(
return body.value;
case ScoreDataTypeEnum.CATEGORICAL:
return body.stringValue;
+ case ScoreDataTypeEnum.CORRECTION:
+ throw new Error("CORRECTION type not supported in annotation drawer");
}
}
diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.ts
index 6af64cc6ef..bc9d96b821 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -218,6 +218,7 @@ export const scoreRecordBaseSchema = z.object({
config_id: z.string().nullish(),
data_type: z.string(),
string_value: z.string().nullish(),
+ long_string_value: z.string(),
queue_id: z.string().nullish(),
execution_trace_id: z.string().nullish(),
is_deleted: z.number(),
@@ -614,6 +615,7 @@ export const convertPostgresScoreToInsert = (
config_id: score.config_id,
data_type: score.data_type,
string_value: score.string_value,
+ long_string_value: "",
queue_id: score.queue_id,
execution_trace_id: null, // Postgres scores do not have eval execution traces
created_at: score.created_at?.getTime(),
diff --git a/packages/shared/src/server/repositories/environments.ts b/packages/shared/src/server/repositories/environments.ts
index d18ab14998..52d7542c93 100644
--- a/packages/shared/src/server/repositories/environments.ts
+++ b/packages/shared/src/server/repositories/environments.ts
@@ -1,3 +1,4 @@
+import { AGGREGATABLE_SCORE_TYPES } from "../../domain/scores";
import { queryClickhouse } from "./clickhouse";
export type EnvironmentFilterProps = {
@@ -25,15 +26,20 @@ export const getEnvironmentsForProject = async (
SELECT distinct environment
FROM scores
WHERE project_id = {projectId: String}
+ AND data_type IN ({dataTypes: Array(String)})
${fromTimestamp ? "AND timestamp >= {fromTimestamp: DateTime64(3)}" : ""}
- )
+ )
`;
const results = await queryClickhouse<{
environment: string;
}>({
query,
- params: { projectId, fromTimestamp },
+ params: {
+ projectId,
+ fromTimestamp,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
+ },
tags: {
feature: "tracing",
type: "environment",
diff --git a/packages/shared/src/server/repositories/scores-utils.ts b/packages/shared/src/server/repositories/scores-utils.ts
index 4823b25e9c..7b0e458142 100644
--- a/packages/shared/src/server/repositories/scores-utils.ts
+++ b/packages/shared/src/server/repositories/scores-utils.ts
@@ -1,4 +1,4 @@
-import { ScoreDomain, ScoreSourceType } from "../../domain";
+import { ScoreDataTypeType, ScoreDomain, ScoreSourceType } from "../../domain";
import { PreferredClickhouseService } from "../clickhouse/client";
import { queryClickhouse } from "./clickhouse";
import { ScoreRecordReadType } from "./definitions";
@@ -14,12 +14,14 @@ export const _handleGetScoreById = async ({
scoreId,
source,
scoreScope,
+ scoreDataTypes,
preferredClickhouseService,
}: {
projectId: string;
scoreId: string;
source?: ScoreSourceType;
scoreScope: "traces_only" | "all";
+ scoreDataTypes?: readonly ScoreDataTypeType[];
preferredClickhouseService?: PreferredClickhouseService;
}): Promise<ScoreDomain | undefined> => {
const query = `
@@ -27,6 +29,7 @@ export const _handleGetScoreById = async ({
FROM scores s
WHERE s.project_id = {projectId: String}
AND s.id = {scoreId: String}
+ ${scoreDataTypes ? `AND s.data_type IN ({scoreDataTypes: Array(String)})` : ""}
${source ? `AND s.source = {source: String}` : ""}
${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}
ORDER BY s.event_ts DESC
@@ -40,6 +43,9 @@ export const _handleGetScoreById = async ({
projectId,
scoreId,
...(source !== undefined ? { source } : {}),
+ ...(scoreDataTypes
+ ? { scoreDataTypes: scoreDataTypes.map((d) => d.toString()) }
+ : {}),
},
tags: {
feature: "tracing",
@@ -62,11 +68,13 @@ export const _handleGetScoresByIds = async ({
scoreId,
source,
scoreScope,
+ dataTypes,
}: {
projectId: string;
scoreId: string[];
source?: ScoreSourceType;
scoreScope: "traces_only" | "all";
+ dataTypes?: readonly ScoreDataTypeType[];
}): Promise<ScoreDomain[]> => {
const query = `
SELECT *
@@ -75,6 +83,7 @@ export const _handleGetScoresByIds = async ({
AND s.id IN ({scoreId: Array(String)})
${source ? `AND s.source = {source: String}` : ""}
${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}
+ ${dataTypes ? `AND s.data_type IN ({dataTypes: Array(String)})` : ""}
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
`;
@@ -84,6 +93,7 @@ export const _handleGetScoresByIds = async ({
params: {
projectId,
scoreId,
+ ...(dataTypes ? { dataTypes: dataTypes.map((d) => d.toString()) } : {}),
...(source !== undefined ? { source } : {}),
},
tags: {
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 3c415709c6..bb58b5e65b 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -2,6 +2,8 @@ import {
ScoreDataTypeType,
ScoreDomain,
ScoreSourceType,
+ AGGREGATABLE_SCORE_TYPES,
+ AggregatableScoreDataType,
} from "../../domain/scores";
import {
commandClickhouse,
@@ -121,6 +123,7 @@ export const getScoresByIds = async (
scoreId,
source,
scoreScope: "all",
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
});
};
@@ -224,6 +227,7 @@ export const getScoresForSessions = async <
from scores s
WHERE s.project_id = {projectId: String}
AND s.session_id IN ({sessionIds: Array(String)})
+ AND s.data_type IN ({dataTypes: Array(String)})
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
${limit && offset ? `limit {limit: Int32} offset {offset: Int32}` : ""}
@@ -236,6 +240,7 @@ export const getScoresForSessions = async <
sessionIds,
limit,
offset,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
},
tags: {
feature: "sessions",
@@ -276,6 +281,7 @@ export const getScoresForDatasetRuns = async <
from scores s
WHERE s.project_id = {projectId: String}
AND s.dataset_run_id IN ({runIds: Array(String)})
+ AND s.data_type IN ({dataTypes: Array(String)})
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
${limit && offset ? `limit {limit: Int32} offset {offset: Int32}` : ""}
@@ -286,6 +292,7 @@ export const getScoresForDatasetRuns = async <
params: {
projectId,
runIds,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
limit,
offset,
},
@@ -300,7 +307,10 @@ export const getScoresForDatasetRuns = async <
const includeMetadataPayload = excludeMetadata ? false : true;
return rows.map((row) =>
- convertClickhouseScoreToDomain(row, includeMetadataPayload),
+ convertClickhouseScoreToDomain<ExcludeMetadata, AggregatableScoreDataType>(
+ row,
+ includeMetadataPayload,
+ ),
);
};
@@ -342,6 +352,7 @@ export const getTraceScoresForDatasetRuns = async (
WHERE dri.project_id = {projectId: String}
AND dri.dataset_run_id IN {datasetRunIds: Array(String)}
AND s.project_id = {projectId: String}
+ AND s.data_type IN ({dataTypes: Array(String)})
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id, dri.dataset_run_id
`;
@@ -356,6 +367,7 @@ export const getTraceScoresForDatasetRuns = async (
params: {
projectId,
datasetRunIds,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
},
tags: {
feature: "dataset-run-items",
@@ -403,6 +415,7 @@ export const getScoresForTraces = async <
from scores s
WHERE s.project_id = {projectId: String}
AND s.trace_id IN ({traceIds: Array(String)})
+ AND s.data_type IN ({dataTypes: Array(String)})
${timestamp ? `AND s.timestamp >= {traceTimestamp: DateTime64(3)} - ${SCORE_TO_TRACE_OBSERVATIONS_INTERVAL}` : ""}
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
@@ -424,6 +437,7 @@ export const getScoresForTraces = async <
traceIds,
limit,
offset,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
...(timestamp
? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
: {}),
@@ -509,6 +523,7 @@ export const getScoresForObservations = async <
from scores s
WHERE s.project_id = {projectId: String}
AND s.observation_id IN ({observationIds: Array(String)})
+ AND s.data_type IN ({dataTypes: Array(String)})
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
@@ -527,6 +542,7 @@ export const getScoresForObservations = async <
params: {
projectId: projectId,
observationIds: observationIds,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
limit: limit,
offset: offset,
},
@@ -593,6 +609,7 @@ export const getScoresGroupedByNameSourceType = async ({
${scoresFilterRes?.query ? `AND ${scoresFilterRes.query}` : ""}
${fromTimestamp ? `AND s.timestamp >= {fromTimestamp: DateTime64(3)}` : ""}
${toTimestamp ? `AND s.timestamp <= {toTimestamp: DateTime64(3)}` : ""}
+ AND s.data_type IN ({dataTypes: Array(String)})
GROUP BY name, source, data_type
ORDER BY count() desc
LIMIT 1000;
@@ -606,6 +623,7 @@ export const getScoresGroupedByNameSourceType = async ({
query: query,
params: {
projectId: projectId,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
...(fromTimestamp
? { fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp) }
: {}),
@@ -625,7 +643,7 @@ export const getScoresGroupedByNameSourceType = async ({
return rows.map((row) => ({
name: row.name,
source: row.source as ScoreSourceType,
- dataType: row.data_type as ScoreDataTypeType,
+ dataType: row.data_type as AggregatableScoreDataType,
}));
};
@@ -871,7 +889,12 @@ export async function getScoresUiTable<
const includeMetadataPayload = excludeMetadata ? false : true;
return rows.map((row) => {
const score = convertClickhouseScoreToDomain(
- { ...row, metadata: excludeMetadata ? {} : row.metadata },
+ {
+ ...row,
+ metadata: excludeMetadata ? {} : row.metadata,
+ // Long string value is never required for scores UI table, so we always return an empty string
+ long_string_value: "",
+ },
includeMetadataPayload,
);
return {
@@ -964,6 +987,7 @@ const getScoresUiGeneric = async <T>(props: {
FROM scores s final
${performTracesJoin ? "LEFT JOIN traces t ON s.trace_id = t.id AND t.project_id = s.project_id" : ""}
WHERE s.project_id = {projectId: String}
+ AND s.data_type IN ({dataTypes: Array(String)})
${scoresFilterRes?.query ? `AND ${scoresFilterRes.query}` : ""}
${orderByToClickhouseSql(orderBy ?? null, scoresTableUiColumnDefinitions)}
${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
@@ -975,6 +999,7 @@ const getScoresUiGeneric = async <T>(props: {
input: {
params: {
projectId: projectId,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
...(scoresFilterRes ? scoresFilterRes.params : {}),
limit: limit,
offset: offset,
@@ -1020,6 +1045,7 @@ export const getScoreNames = async (
from scores s
WHERE s.project_id = {projectId: String}
${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
+ AND s.data_type IN ({dataTypes: Array(String)})
GROUP BY name
ORDER BY count() desc
LIMIT 1000;
@@ -1033,6 +1059,7 @@ export const getScoreNames = async (
params: {
projectId: projectId,
...(timestampFilterRes ? timestampFilterRes.params : {}),
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
},
tags: {
feature: "tracing",
@@ -1281,6 +1308,7 @@ export const getAggregatedScoresForPrompts = async (
AND o.type = 'GENERATION'
AND s.name IS NOT NULL
${fetchScoreRelation === "trace" ? "AND s.observation_id IS NULL" : ""}
+ AND s.data_type IN ({dataTypes: Array(String)})
`;
const rows = await queryClickhouse<
@@ -1294,6 +1322,7 @@ export const getAggregatedScoresForPrompts = async (
params: {
projectId,
promptIds,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
},
tags: {
feature: "tracing",
@@ -1304,7 +1333,7 @@ export const getAggregatedScoresForPrompts = async (
});
return rows.map((row) => ({
- ...convertScoreAggregation(row),
+ ...convertScoreAggregation<AggregatableScoreDataType>(row),
promptId: row.prompt_id,
hasMetadata: !!row.has_metadata,
}));
@@ -1324,6 +1353,7 @@ export const getScoreCountsByProjectInCreationInterval = async ({
FROM scores
WHERE created_at >= {start: DateTime64(3)}
AND created_at < {end: DateTime64(3)}
+ AND data_type IN ({dataTypes: Array(String)})
GROUP BY project_id
`;
@@ -1332,6 +1362,7 @@ export const getScoreCountsByProjectInCreationInterval = async ({
params: {
start: convertDateToClickhouseDateTime(start),
end: convertDateToClickhouseDateTime(end),
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
},
tags: {
feature: "tracing",
@@ -1399,6 +1430,7 @@ export const getDistinctScoreNames = async (p: {
WHERE s.project_id = {projectId: String}
AND s.created_at <= {cutoffCreatedAt: DateTime64(3)}
${scoreTimestampFilter ? `AND s.timestamp >= {filterTimestamp: DateTime64(3)}` : ""}
+ AND s.data_type IN ({dataTypes: Array(String)})
`;
const rows = await queryClickhouse<{ name: string }>({
@@ -1406,6 +1438,7 @@ export const getDistinctScoreNames = async (p: {
params: {
projectId,
cutoffCreatedAt: convertDateToClickhouseDateTime(cutoffCreatedAt),
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
...(scoreTimestampFilter
? {
filterTimestamp: convertDateToClickhouseDateTime(
@@ -1449,6 +1482,7 @@ export const getScoresForBlobStorageExport = function (
WHERE project_id = {projectId: String}
AND timestamp >= {minTimestamp: DateTime64(3)}
AND timestamp <= {maxTimestamp: DateTime64(3)}
+ AND data_type IN ({dataTypes: Array(String)})
`;
const records = queryClickhouseStream<Record<string, unknown>>({
@@ -1457,6 +1491,7 @@ export const getScoresForBlobStorageExport = function (
projectId,
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
},
tags: {
feature: "blobstorage",
@@ -1506,6 +1541,7 @@ export const getScoresForAnalyticsIntegrations = async function* (
WHERE s.project_id = {projectId: String}
AND s.timestamp >= {minTimestamp: DateTime64(3)}
AND s.timestamp <= {maxTimestamp: DateTime64(3)}
+ AND s.data_type IN ({dataTypes: Array(String)})
AND (
s.trace_id IS NOT NULL
OR s.session_id IS NOT NULL
@@ -1527,6 +1563,7 @@ export const getScoresForAnalyticsIntegrations = async function* (
projectId,
minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
},
tags: {
feature: "posthog",
@@ -1685,6 +1722,7 @@ export const getScoreCountsByProjectAndDay = async ({
FROM scores
WHERE timestamp >= {startDate: DateTime64(3)}
AND timestamp < {endDate: DateTime64(3)}
+ AND data_type IN ({dataTypes: Array(String)})
GROUP BY project_id, toDate(timestamp)
`;
@@ -1697,6 +1735,7 @@ export const getScoreCountsByProjectAndDay = async ({
params: {
startDate: convertDateToClickhouseDateTime(startDate),
endDate: convertDateToClickhouseDateTime(endDate),
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
},
tags: {
feature: "tracing",
diff --git a/packages/shared/src/server/repositories/scores_converters.ts b/packages/shared/src/server/repositories/scores_converters.ts
index 9b04a51758..1623e8c8e8 100644
--- a/packages/shared/src/server/repositories/scores_converters.ts
+++ b/packages/shared/src/server/repositories/scores_converters.ts
@@ -1,7 +1,7 @@
import { ScoreRecordReadType } from "./definitions";
import type {
ScoreDataTypeType,
- ScoreDomain,
+ ScoreByDataType,
ScoreSourceType,
} from "../../domain/scores";
import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";
@@ -18,10 +18,13 @@ export type ScoreAggregation = {
timestamp: Date;
};
-export const convertClickhouseScoreToDomain = <ExcludeMetadata extends boolean>(
+export const convertClickhouseScoreToDomain = <
+ ExcludeMetadata extends boolean = false,
+ DataType extends ScoreDataTypeType = ScoreDataTypeType,
+>(
record: ScoreRecordReadType,
includeMetadataPayload: boolean = true,
-): ScoreDomain => {
+): ScoreByDataType<DataType> => {
const baseScore = {
id: record.id,
timestamp: parseClickhouseUTCDateTimeFormat(record.timestamp),
@@ -33,11 +36,12 @@ export const convertClickhouseScoreToDomain = <ExcludeMetadata extends boolean>(
datasetRunId: record.dataset_run_id ?? null,
name: record.name,
value: record.value,
+ longStringValue: record.long_string_value ?? "",
source: record.source as ScoreSourceType,
comment: record.comment ?? null,
authorUserId: record.author_user_id ?? null,
configId: record.config_id ?? null,
- dataType: record.data_type as ScoreDataTypeType,
+ dataType: record.data_type as DataType,
queueId: record.queue_id ?? null,
executionTraceId: record.execution_trace_id ?? null,
createdAt: record.created_at
@@ -54,24 +58,38 @@ export const convertClickhouseScoreToDomain = <ExcludeMetadata extends boolean>(
};
if (record.data_type === "NUMERIC") {
- return { ...baseScore, dataType: "NUMERIC", stringValue: null };
+ return {
+ ...baseScore,
+ dataType: "NUMERIC" as DataType,
+ stringValue: null,
+ } as ScoreByDataType<DataType>;
+ }
+
+ if (record.data_type === "CORRECTION") {
+ return {
+ ...baseScore,
+ dataType: "CORRECTION" as DataType,
+ stringValue: null,
+ } as ScoreByDataType<DataType>;
}
return {
...baseScore,
- dataType: record.data_type as "CATEGORICAL" | "BOOLEAN",
+ dataType: record.data_type as DataType,
stringValue: record.string_value!,
- };
+ } as ScoreByDataType<DataType>;
};
-export const convertScoreAggregation = (row: ScoreAggregation) => {
+export const convertScoreAggregation = <DataType extends ScoreDataTypeType>(
+ row: ScoreAggregation,
+) => {
return {
id: row.id,
name: row.name,
stringValue: row.string_value,
value: Number(row.value),
source: row.source as ScoreSourceType,
- dataType: row.data_type as ScoreDataTypeType,
+ dataType: row.data_type as DataType,
comment: row.comment,
timestamp: row.timestamp,
};
diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.ts
index 8b301c19b9..217d7c808f 100644
--- a/packages/shared/src/server/test-utils/tracing-factory.ts
+++ b/packages/shared/src/server/test-utils/tracing-factory.ts
@@ -118,6 +118,7 @@ export const createTraceScore = (
timestamp: Date.now(),
value: 100.5,
string_value: null,
+ long_string_value: "",
source: "API",
comment: "comment",
metadata: { "test-key": "test-value" },
@@ -143,6 +144,7 @@ export const createSessionScore = (
name: "test-session-score" + v4(),
timestamp: Date.now(),
value: 100.5,
+ long_string_value: "",
source: "API",
comment: "comment",
metadata: { "test-key": "test-value" },
@@ -169,6 +171,7 @@ export const createDatasetRunScore = (
name: "test-run-score" + v4(),
timestamp: Date.now(),
value: 100.5,
+ long_string_value: "",
source: "API",
comment: "comment",
metadata: { "test-key": "test-value" },
diff --git a/web/public/generated/api-client/openapi.yml b/web/public/generated/api-client/openapi.yml
index dcd9697b8f..73df3f3bab 100644
--- a/web/public/generated/api-client/openapi.yml
+++ b/web/public/generated/api-client/openapi.yml
@@ -68,6 +68,9 @@ components:
nullable: true
name:
type: string
+ description: >-
+ The name of the score. Always overrides "output" for correction
+ scores.
example: novelty
value:
$ref: '#/components/schemas/CreateScoreValue'
@@ -105,6 +108,7 @@ components:
- NUMERIC
- CATEGORICAL
- BOOLEAN
+ - CORRECTION
CreateScoreValue:
title: CreateScoreValue
oneOf:
@@ -113,7 +117,8 @@ components:
- type: string
description: >-
The value of the score. Must be passed as string for categorical scores,
- and numeric for boolean and numeric scores
+ and numeric for boolean and numeric scores. For corrections pass value
+ as string and set data type to CORRECTION
securitySchemes:
BearerAuth:
type: http
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index bd1e4a8a76..ee987af531 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -6758,7 +6758,7 @@ components:
projectId:
type: string
dataType:
- $ref: '#/components/schemas/ScoreDataType'
+ $ref: '#/components/schemas/ScoreConfigDataType'
isArchived:
type: boolean
description: Whether the score config is archived. Defaults to false
@@ -7816,6 +7816,13 @@ components:
- ANNOTATION
- API
- EVAL
+ ScoreConfigDataType:
+ title: ScoreConfigDataType
+ type: string
+ enum:
+ - NUMERIC
+ - BOOLEAN
+ - CATEGORICAL
ScoreDataType:
title: ScoreDataType
type: string
@@ -7823,6 +7830,7 @@ components:
- NUMERIC
- BOOLEAN
- CATEGORICAL
+ - CORRECTION
DeleteDatasetItemResponse:
title: DeleteDatasetItemResponse
type: object
@@ -8412,6 +8420,9 @@ components:
nullable: true
name:
type: string
+ description: >-
+ The name of the score. Always overrides "output" for correction
+ scores.
example: novelty
environment:
type: string
@@ -10178,7 +10189,7 @@ components:
name:
type: string
dataType:
- $ref: '#/components/schemas/ScoreDataType'
+ $ref: '#/components/schemas/ScoreConfigDataType'
categories:
type: array
items:
diff --git a/web/src/__tests__/async/scores-api-v1.servertest.ts b/web/src/__tests__/async/scores-api-v1.servertest.ts
index 639406345e..d1b8bd5fbe 100644
--- a/web/src/__tests__/async/scores-api-v1.servertest.ts
+++ b/web/src/__tests__/async/scores-api-v1.servertest.ts
@@ -1083,6 +1083,131 @@ describe("/api/public/scores API Endpoint", () => {
);
}
});
+
+ it("should reject CORRECTION data type filtering", async () => {
+ try {
+ await makeAPICall(
+ "GET",
+ `/api/public/scores?dataType=CORRECTION`,
+ undefined,
+ authentication,
+ );
+ } catch (error) {
+ expect((error as Error).message).toContain(
+ "API call did not return 200, returned status 400",
+ );
+ }
+ });
+
+ it("should exclude CORRECTION scores from list when no dataType filter is provided", async () => {
+ const { projectId, auth } = await createOrgProjectAndApiKey();
+ const traceId = v4();
+
+ const trace = createTrace({
+ id: traceId,
+ project_id: projectId,
+ });
+ await createTracesCh([trace]);
+
+ // Create a NUMERIC score (should be returned)
+ const numericScoreId = v4();
+ const numericScore = createTraceScore({
+ id: numericScoreId,
+ project_id: projectId,
+ trace_id: traceId,
+ name: "numeric-score",
+ value: 95.5,
+ source: "API",
+ data_type: "NUMERIC" as const,
+ });
+
+ // Create a CORRECTION score (should NOT be returned)
+ const correctionScoreId = v4();
+ const correctionScore = createTraceScore({
+ id: correctionScoreId,
+ project_id: projectId,
+ trace_id: traceId,
+ name: "correction-score",
+ value: 0,
+ source: "ANNOTATION",
+ data_type: "CORRECTION" as const,
+ string_value: null,
+ long_string_value: "This is a correction",
+ });
+
+ await createScoresCh([numericScore, correctionScore]);
+
+ // Wait for scores to be available
+ // Note: getScoresByIds only returns aggregatable scores, so we only check for the NUMERIC score
+ await waitForExpect(async () => {
+ const checkScores = await getScoresByIds(projectId, [numericScoreId]);
+ expect(checkScores).toHaveLength(1);
+ });
+
+ // Fetch all scores without filter - should only get NUMERIC
+ const response = await makeZodVerifiedAPICall(
+ GetScoresResponseV1,
+ "GET",
+ `/api/public/scores?page=1&limit=10`,
+ undefined,
+ auth,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toHaveLength(1);
+ expect(response.body.data[0].id).toBe(numericScoreId);
+ expect(response.body.data[0].dataType).toBe("NUMERIC");
+ expect(response.body.meta.totalItems).toBe(1);
+
+ // Verify CORRECTION score is NOT in the results
+ const correctionInResults = response.body.data.find(
+ (s) => s.id === correctionScoreId,
+ );
+ expect(correctionInResults).toBeUndefined();
+ });
+
+ it("should not return CORRECTION score when fetching by ID", async () => {
+ const { projectId, auth } = await createOrgProjectAndApiKey();
+ const traceId = v4();
+
+ const trace = createTrace({
+ id: traceId,
+ project_id: projectId,
+ });
+ await createTracesCh([trace]);
+
+ // Create a CORRECTION score
+ const correctionScoreId = v4();
+ const correctionScore = createTraceScore({
+ id: correctionScoreId,
+ project_id: projectId,
+ trace_id: traceId,
+ name: "correction-score",
+ value: 0,
+ source: "ANNOTATION",
+ data_type: "CORRECTION" as const,
+ string_value: null,
+ long_string_value: "This is a correction",
+ });
+ await createScoresCh([correctionScore]);
+
+ // Wait for score to be available
+ await waitForExpect(async () => {
+ const checkScore = await getScoresByIds(projectId, [
+ correctionScoreId,
+ ]);
+ expect(checkScore).toHaveLength(0);
+ });
+
+ // Try to fetch by ID - should return 404 since v1 doesn't support CORRECTION
+ const response = await makeAPICall(
+ "GET",
+ `/api/public/scores/${correctionScoreId}`,
+ undefined,
+ auth,
+ );
+ expect(response.status).toBe(404);
+ });
});
});
});
diff --git a/web/src/__tests__/async/scores-api-v2.servertest.ts b/web/src/__tests__/async/scores-api-v2.servertest.ts
index 1c6589bdaa..fedbe05067 100644
--- a/web/src/__tests__/async/scores-api-v2.servertest.ts
+++ b/web/src/__tests__/async/scores-api-v2.servertest.ts
@@ -215,6 +215,8 @@ describe("/api/public/v2/scores API Endpoint", () => {
const scoreId_7 = v4();
const scoreId_8 = v4();
const scoreId_9 = v4();
+ const correctionScoreId_1 = v4();
+ const correctionScoreId_2 = v4();
let authentication: string;
let newProjectId: string;
@@ -323,6 +325,26 @@ describe("/api/public/v2/scores API Endpoint", () => {
environment: "production",
});
+ const correction1 = createTraceScore({
+ id: correctionScoreId_1,
+ project_id: newProjectId,
+ trace_id: traceId_2,
+ name: "output",
+ data_type: "CORRECTION",
+ long_string_value: "correction-value-1",
+ environment: "annotation",
+ });
+
+ const correction2 = createTraceScore({
+ id: correctionScoreId_2,
+ project_id: newProjectId,
+ trace_id: traceId_3,
+ name: "output",
+ data_type: "CORRECTION",
+ long_string_value: "correction-value-2",
+ environment: "annotation",
+ });
+
const sessionScore1 = createSessionScore({
id: scoreId_6,
project_id: newProjectId,
@@ -369,6 +391,8 @@ describe("/api/public/v2/scores API Endpoint", () => {
sessionScore2,
runScore1,
runScore2,
+ correction1,
+ correction2,
]);
});
@@ -384,7 +408,7 @@ describe("/api/public/v2/scores API Endpoint", () => {
expect(getAllScore.body.meta).toMatchObject({
page: 1,
limit: 50,
- totalItems: 9,
+ totalItems: 11,
totalPages: 1,
});
for (const val of getAllScore.body.data) {
@@ -458,6 +482,31 @@ describe("/api/public/v2/scores API Endpoint", () => {
}
});
+ it("get all scores for correction data type", async () => {
+ const getAllScore = await makeZodVerifiedAPICall(
+ GetScoresResponseV2,
+ "GET",
+ `/api/public/v2/scores?dataType=CORRECTION`,
+ undefined,
+ authentication,
+ );
+
+ expect(getAllScore.status).toBe(200);
+ expect(getAllScore.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 2,
+ totalPages: 1,
+ });
+ for (const val of getAllScore.body.data) {
+ expect(val).toMatchObject({
+ dataType: "CORRECTION",
+ name: "output",
+ });
+ expect(val.stringValue).toContain("correction-value");
+ }
+ });
+
it("get all scores for trace tag 'prod'", async () => {
const getAllScore = await makeZodVerifiedAPICall(
GetScoresResponseV2,
@@ -523,7 +572,7 @@ describe("/api/public/v2/scores API Endpoint", () => {
expect(getAllScore.body.meta).toMatchObject({
page: 1,
limit: 50,
- totalItems: 1,
+ totalItems: 2,
totalPages: 1,
});
for (const val of getAllScore.body.data) {
diff --git a/web/src/features/dashboard/components/ScoresTable.tsx b/web/src/features/dashboard/components/ScoresTable.tsx
index 0bce3051a2..f83ed880e9 100644
--- a/web/src/features/dashboard/components/ScoresTable.tsx
+++ b/web/src/features/dashboard/components/ScoresTable.tsx
@@ -12,7 +12,11 @@ import { LeftAlignedCell } from "@/src/features/dashboard/components/LeftAligned
import { TotalMetric } from "./TotalMetric";
import { createTracesTimeFilter } from "@/src/features/dashboard/lib/dashboard-utils";
import { getScoreDataTypeIcon } from "@/src/features/scores/lib/scoreColumns";
-import { isCategoricalDataType } from "@/src/features/scores/lib/helpers";
+import {
+ isBooleanDataType,
+ isCategoricalDataType,
+ isNumericDataType,
+} from "@/src/features/scores/lib/helpers";
import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";
import { NoDataOrLoading } from "@/src/components/NoDataOrLoading";
@@ -20,9 +24,11 @@ const dropValuesForCategoricalScores = (
value: number,
scoreDataType: ScoreDataTypeType,
): string => {
- return isCategoricalDataType(scoreDataType)
- ? "-"
- : compactNumberFormatter(value);
+ if (isCategoricalDataType(scoreDataType)) return "-";
+ if (isBooleanDataType(scoreDataType) || isNumericDataType(scoreDataType)) {
+ return compactNumberFormatter(value);
+ }
+ return "-";
};
const scoreNameSourceDataTypeMatch =
diff --git a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
index 9a763aadc7..2702ae3b0a 100644
--- a/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
+++ b/web/src/features/dashboard/components/score-analytics/ScoreAnalytics.tsx
@@ -1,7 +1,6 @@
import { api } from "@/src/utils/api";
-
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
-import { type FilterState } from "@langfuse/shared";
+import { type ScoreDataTypeType, type FilterState } from "@langfuse/shared";
import { type DashboardDateRangeAggregationOption } from "@/src/utils/date-range-utils";
import { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";
import React, { useMemo } from "react";
@@ -131,7 +130,12 @@ export function ScoreAnalytics(props: {
projectId={props.projectId}
source={source}
name={name}
- dataType={dataType}
+ dataType={
+ dataType as Extract<
+ ScoreDataTypeType,
+ "NUMERIC" | "BOOLEAN"
+ >
+ }
globalFilterState={props.globalFilterState}
/>
)}
@@ -159,7 +163,12 @@ export function ScoreAnalytics(props: {
agg={props.agg}
source={source}
name={name}
- dataType={dataType}
+ dataType={
+ dataType as Extract<
+ ScoreDataTypeType,
+ "NUMERIC" | "BOOLEAN"
+ >
+ }
projectId={props.projectId}
globalFilterState={props.globalFilterState}
fromTimestamp={props.fromTimestamp}
diff --git a/web/src/features/datasets/server/service.ts b/web/src/features/datasets/server/service.ts
index e01c700f66..d916f0d3cd 100644
--- a/web/src/features/datasets/server/service.ts
+++ b/web/src/features/datasets/server/service.ts
@@ -7,6 +7,7 @@ import {
type TracingSearchType,
singleFilter,
type DatasetRunItemDomain,
+ AGGREGATABLE_SCORE_TYPES,
} from "@langfuse/shared";
import { z } from "zod/v4";
import {
@@ -140,6 +141,7 @@ export const getRunItemsByRunIdOrItemId = async <WithIO extends boolean = true>(
const validatedTraceScores = filterAndValidateDbScoreList({
scores: traceScores,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
includeHasMetadata: true,
onParseError: traceException,
});
diff --git a/web/src/features/public-api/server/scores-api-service.ts b/web/src/features/public-api/server/scores-api-service.ts
index a732e24550..9f25d391ce 100644
--- a/web/src/features/public-api/server/scores-api-service.ts
+++ b/web/src/features/public-api/server/scores-api-service.ts
@@ -1,9 +1,13 @@
import {
_handleGenerateScoresForPublicApi,
_handleGetScoresCountForPublicApi,
+ convertScoreToPublicApi,
type ScoreQueryType,
} from "@/src/features/public-api/server/scores";
-import { type ScoreSourceType } from "@langfuse/shared";
+import {
+ AGGREGATABLE_SCORE_TYPES,
+ type ScoreSourceType,
+} from "@langfuse/shared";
import { _handleGetScoreById } from "@langfuse/shared/src/server";
export class ScoresApiService {
@@ -11,6 +15,8 @@ export class ScoresApiService {
/**
* Get a specific score by ID
+ * v1: Only returns aggregatable scores (NUMERIC, BOOLEAN, CATEGORICAL) - excludes CORRECTION
+ * v2: Returns all score types including CORRECTION
*/
async getScoreById({
projectId,
@@ -21,32 +27,48 @@ export class ScoresApiService {
scoreId: string;
source?: ScoreSourceType;
}) {
- return _handleGetScoreById({
+ const score = await _handleGetScoreById({
projectId,
scoreId,
source,
scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",
+ scoreDataTypes:
+ this.apiVersion === "v1" ? AGGREGATABLE_SCORE_TYPES : undefined,
preferredClickhouseService: "ReadOnly",
});
+
+ if (!score) {
+ return undefined;
+ }
+
+ return convertScoreToPublicApi(score);
}
/**
* Get list of scores with version-aware filtering
+ * v1: Only returns aggregatable scores (NUMERIC, BOOLEAN, CATEGORICAL) - excludes CORRECTION
+ * v2: Returns all score types including CORRECTION
*/
async generateScoresForPublicApi(props: ScoreQueryType) {
return _handleGenerateScoresForPublicApi({
props,
scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",
+ scoreDataTypes:
+ this.apiVersion === "v1" ? AGGREGATABLE_SCORE_TYPES : undefined,
});
}
/**
* Get count of scores with version-aware filtering
+ * v1: Only counts aggregatable scores (NUMERIC, BOOLEAN, CATEGORICAL) - excludes CORRECTION
+ * v2: Counts all score types including CORRECTION
*/
async getScoresCountForPublicApi(props: ScoreQueryType) {
return _handleGetScoresCountForPublicApi({
props,
scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",
+ scoreDataTypes:
+ this.apiVersion === "v1" ? AGGREGATABLE_SCORE_TYPES : undefined,
});
}
}
diff --git a/web/src/features/public-api/server/scores.ts b/web/src/features/public-api/server/scores.ts
index 7b98ece147..379a939a0a 100644
--- a/web/src/features/public-api/server/scores.ts
+++ b/web/src/features/public-api/server/scores.ts
@@ -2,10 +2,36 @@ import { convertApiProvidedFilterToClickhouseFilter } from "@langfuse/shared/src
import {
convertClickhouseScoreToDomain,
StringFilter,
+ StringOptionsFilter,
type ScoreRecordReadType,
queryClickhouse,
measureAndReturn,
} from "@langfuse/shared/src/server";
+import {
+ removeObjectKeys,
+ ScoreDataTypeEnum,
+ type ScoreDataTypeType,
+ type ScoreDomain,
+} from "@langfuse/shared";
+
+/**
+ * Converts a ScoreDomain object to API format.
+ * For CORRECTION scores, moves longStringValue to stringValue for API compatibility.
+ * For other score types, removes longStringValue.
+ */
+export const convertScoreToPublicApi = <T extends ScoreDomain>(
+ score: T,
+): Omit<T, "longStringValue"> & { stringValue?: string | null } => {
+ if (score.dataType === ScoreDataTypeEnum.CORRECTION) {
+ const { longStringValue, ...rest } = score;
+ return {
+ ...rest,
+ stringValue: longStringValue,
+ };
+ }
+
+ return removeObjectKeys(score, ["longStringValue"]);
+};
export type ScoreQueryType = {
page: number;
@@ -37,11 +63,16 @@ export type ScoreQueryType = {
export const _handleGenerateScoresForPublicApi = async ({
props,
scoreScope,
+ scoreDataTypes,
}: {
props: ScoreQueryType;
scoreScope: "traces_only" | "all";
+ scoreDataTypes?: readonly ScoreDataTypeType[];
}) => {
- const { scoresFilter, tracesFilter } = generateScoreFilter(props);
+ const { scoresFilter, tracesFilter } = generateScoreFilter(
+ props,
+ scoreDataTypes,
+ );
const appliedScoresFilter = scoresFilter.apply();
const appliedTracesFilter = tracesFilter.apply();
@@ -57,6 +88,7 @@ export const _handleGenerateScoresForPublicApi = async ({
s.name as name,
s.value as value,
s.string_value as string_value,
+ s.long_string_value as long_string_value,
s.author_user_id as author_user_id,
s.created_at as created_at,
s.updated_at as updated_at,
@@ -139,17 +171,21 @@ export const _handleGenerateScoresForPublicApi = async ({
preferredClickhouseService: "ReadOnly",
});
- return records.map((record) => ({
- ...convertClickhouseScoreToDomain(record),
- trace:
- record.trace_id !== null
- ? {
- userId: record.user_id,
- tags: record.tags,
- environment: record.trace_environment,
- }
- : null,
- }));
+ return records.map((record) => {
+ const domainScore = convertClickhouseScoreToDomain(record);
+ const apiScore = convertScoreToPublicApi(domainScore);
+ return {
+ ...apiScore,
+ trace:
+ record.trace_id !== null
+ ? {
+ userId: record.user_id,
+ tags: record.tags,
+ environment: record.trace_environment,
+ }
+ : null,
+ };
+ });
},
});
};
@@ -162,11 +198,16 @@ export const _handleGenerateScoresForPublicApi = async ({
export const _handleGetScoresCountForPublicApi = async ({
props,
scoreScope,
+ scoreDataTypes,
}: {
props: ScoreQueryType;
scoreScope: "traces_only" | "all";
+ scoreDataTypes?: readonly ScoreDataTypeType[];
}) => {
- const { scoresFilter, tracesFilter } = generateScoreFilter(props);
+ const { scoresFilter, tracesFilter } = generateScoreFilter(
+ props,
+ scoreDataTypes,
+ );
const appliedScoresFilter = scoresFilter.apply();
const appliedTracesFilter = tracesFilter.apply();
@@ -351,7 +392,10 @@ const secureTraceFilterOptions = [
},
];
-const generateScoreFilter = (filter: ScoreQueryType) => {
+const generateScoreFilter = (
+ filter: ScoreQueryType,
+ scoreDataTypes?: readonly ScoreDataTypeType[],
+) => {
const scoresFilter = convertApiProvidedFilterToClickhouseFilter(
filter,
secureScoreFilterOptions,
@@ -365,6 +409,20 @@ const generateScoreFilter = (filter: ScoreQueryType) => {
}),
);
+ // Add version-based dataType restriction if provided
+ // This will AND with any user-provided dataType filter for proper intersection
+ if (scoreDataTypes) {
+ scoresFilter.push(
+ new StringOptionsFilter({
+ clickhouseTable: "scores",
+ field: "data_type",
+ operator: "any of",
+ values: [...scoreDataTypes],
+ tablePrefix: "s",
+ }),
+ );
+ }
+
const tracesFilter = convertApiProvidedFilterToClickhouseFilter(
filter,
secureTraceFilterOptions,
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index 0a1db227b9..3cf5f6f4e7 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -12,7 +12,7 @@ import {
tracesTableUiColumnDefinitions,
shouldSkipObservationsFinal,
} from "@langfuse/shared/src/server";
-import { type OrderByState } from "@langfuse/shared";
+import { AGGREGATABLE_SCORE_TYPES, type OrderByState } from "@langfuse/shared";
import {
TRACE_FIELD_GROUPS,
type TraceFieldGroup,
@@ -189,6 +189,7 @@ async function buildTracesBaseQuery(
WHERE project_id = {projectId: String}
AND session_id IS NULL
AND dataset_run_id IS NULL
+ AND data_type IN ({dataTypes: Array(String)})
${fromTimeFilter ? `AND timestamp >= {cteFromTimeFilter: DateTime64(3)}` : ""}
${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
GROUP BY
@@ -215,6 +216,7 @@ async function buildTracesBaseQuery(
WHERE project_id = {projectId: String}
AND session_id IS NULL
AND dataset_run_id IS NULL
+ AND data_type IN ({dataTypes: Array(String)})
${fromTimeFilter ? `AND timestamp >= {cteFromTimeFilter: DateTime64(3)}` : ""}
${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
GROUP BY project_id, trace_id
@@ -285,6 +287,7 @@ async function buildTracesBaseQuery(
...appliedEnvironmentFilter.params,
...appliedFilter.params,
projectId: props.projectId,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
...(props.limit !== undefined ? { limit: props.limit } : {}),
...(props.page !== undefined
? { offset: (props.page - 1) * props.limit }
diff --git a/web/src/features/scores/contexts/ScoreCacheContext.tsx b/web/src/features/scores/contexts/ScoreCacheContext.tsx
index 13f3306a40..f2e6daea67 100644
--- a/web/src/features/scores/contexts/ScoreCacheContext.tsx
+++ b/web/src/features/scores/contexts/ScoreCacheContext.tsx
@@ -6,7 +6,10 @@ import {
useContext,
useState,
} from "react";
-import { type ScoreColumn } from "@/src/features/scores/types";
+import {
+ type AnnotationScoreDataType,
+ type ScoreColumn,
+} from "@/src/features/scores/types";
import { composeAggregateScoreKey } from "@/src/features/scores/lib/aggregateScores";
/**
@@ -21,7 +24,6 @@ export type CachedScore = Pick<
| "environment"
// Score identity
| "name"
- | "dataType"
// Score values
| "value"
| "stringValue"
@@ -35,6 +37,7 @@ export type CachedScore = Pick<
// Score identity - non-nullable
configId: string;
source: "ANNOTATION";
+ dataType: AnnotationScoreDataType;
};
type ScoreCacheContextValue = {
diff --git a/web/src/features/scores/lib/aggregateScores.ts b/web/src/features/scores/lib/aggregateScores.ts
index 6efd95fedd..7714335a28 100644
--- a/web/src/features/scores/lib/aggregateScores.ts
+++ b/web/src/features/scores/lib/aggregateScores.ts
@@ -4,7 +4,7 @@ import {
type ScoreSimplified,
type ScoreSourceType,
type ScoreDomain,
- type ScoreDataTypeType,
+ type AggregatableScoreDataType,
} from "@langfuse/shared";
/**
@@ -22,7 +22,7 @@ export const composeAggregateScoreKey = ({
}: {
name: string;
source: ScoreSourceType;
- dataType: ScoreDataTypeType;
+ dataType: AggregatableScoreDataType;
keyPrefix?: string;
}): string => {
const formattedName = normalizeScoreName(name);
@@ -34,13 +34,13 @@ export const decomposeAggregateScoreKey = (
): {
name: string;
source: ScoreSourceType;
- dataType: ScoreDataTypeType;
+ dataType: AggregatableScoreDataType;
} => {
const [name, source, dataType] = key.split("-");
return {
name,
source: source as ScoreSourceType,
- dataType: dataType as ScoreDataTypeType,
+ dataType: dataType as AggregatableScoreDataType,
};
};
@@ -49,9 +49,14 @@ export const getScoreLabelFromKey = (key: string): string => {
return `${getScoreDataTypeIcon(dataType)} ${name} (${source.toLowerCase()})`;
};
-type ScoreToAggregate = (ScoreDomain | ScoreSimplified) & {
- hasMetadata?: boolean;
-};
+export type ScoreToAggregate =
+ | (Omit<ScoreDomain, "dataType"> & {
+ dataType: AggregatableScoreDataType;
+ hasMetadata?: boolean;
+ })
+ | (ScoreSimplified & {
+ hasMetadata?: boolean;
+ });
/**
* Maps score data types to aggregate types for processing.
@@ -59,7 +64,7 @@ type ScoreToAggregate = (ScoreDomain | ScoreSimplified) & {
* aggregation logic (value counting vs numeric averaging).
*/
export const resolveAggregateType = (
- dataType: ScoreDataTypeType,
+ dataType: AggregatableScoreDataType,
): "NUMERIC" | "CATEGORICAL" => {
return dataType === "BOOLEAN" ? "CATEGORICAL" : dataType;
};
diff --git a/web/src/features/scores/lib/scoreColumns.ts b/web/src/features/scores/lib/scoreColumns.ts
index 5e4f33916b..93fd9c1e4f 100644
--- a/web/src/features/scores/lib/scoreColumns.ts
+++ b/web/src/features/scores/lib/scoreColumns.ts
@@ -127,6 +127,8 @@ export const getScoreDataTypeIcon = (dataType: ScoreDataTypeType): string => {
return "â’¸";
case "BOOLEAN":
return "â’·";
+ case "CORRECTION":
+ throw new Error("CORRECTION type not supported");
}
};
diff --git a/web/src/features/scores/lib/transformScores.ts b/web/src/features/scores/lib/transformScores.ts
index 7828882fae..92b058a02a 100644
--- a/web/src/features/scores/lib/transformScores.ts
+++ b/web/src/features/scores/lib/transformScores.ts
@@ -1,6 +1,10 @@
import { type ScoreDomain, type ScoreConfigDomain } from "@langfuse/shared";
import { type ScoreAggregate } from "@langfuse/shared";
-import { type AnnotationScore } from "@/src/features/scores/types";
+import {
+ ANNOTATION_SCORE_DATA_TYPES_ARRAY,
+ type AnnotationScoreDataType,
+ type AnnotationScore,
+} from "@/src/features/scores/types";
import {
decomposeAggregateScoreKey,
normalizeScoreName,
@@ -63,7 +67,13 @@ function transformFlatScores(
configs: ScoreConfigDomain[],
): AnnotationScore[] {
return mergedScores
- .filter((score) => score.source === "ANNOTATION")
+ .filter(
+ (score) =>
+ score.source === "ANNOTATION" &&
+ ANNOTATION_SCORE_DATA_TYPES_ARRAY.includes(
+ score.dataType as AnnotationScoreDataType,
+ ),
+ )
.map((score) => {
const config = configs.find((c) => c.id === score.configId);
if (!config || !score.configId) return null;
@@ -71,7 +81,7 @@ function transformFlatScores(
return {
id: score.id,
name: score.name,
- dataType: score.dataType,
+ dataType: score.dataType as AnnotationScoreDataType,
source: score.source,
configId: score.configId,
value: score.value,
diff --git a/web/src/features/scores/schema.ts b/web/src/features/scores/schema.ts
index ff785a23cd..efdff12df9 100644
--- a/web/src/features/scores/schema.ts
+++ b/web/src/features/scores/schema.ts
@@ -1,4 +1,4 @@
-import { ScoreDataTypeArray } from "@langfuse/shared";
+import { ANNOTATION_SCORE_DATA_TYPES_ARRAY } from "@/src/features/scores/types";
import { z } from "zod/v4";
export const AnnotationScoreDataSchema = z.object({
@@ -9,7 +9,7 @@ export const AnnotationScoreDataSchema = z.object({
name: z.string(),
value: z.number().nullish(),
stringValue: z.string().nullish(),
- dataType: z.enum(ScoreDataTypeArray),
+ dataType: z.enum(ANNOTATION_SCORE_DATA_TYPES_ARRAY),
configId: z.string(),
comment: z.string().nullish(),
});
diff --git a/web/src/features/scores/types.ts b/web/src/features/scores/types.ts
index 25423c9c74..49556400b6 100644
--- a/web/src/features/scores/types.ts
+++ b/web/src/features/scores/types.ts
@@ -7,6 +7,8 @@ import {
type ScoreAggregate,
type ScoreConfigDomain,
type ScoreDomain,
+ type AggregatableScoreDataType,
+ ScoreConfigDataType,
} from "@langfuse/shared";
import { type z } from "zod/v4";
@@ -56,7 +58,7 @@ export type ScoreTarget = SessionScoreTarget | TraceScoreTarget;
export type AnnotationScore = {
id: string | null;
name: string;
- dataType: ScoreDataTypeType;
+ dataType: AnnotationScoreDataType;
source: ScoreSourceType;
value?: number | null;
stringValue?: string | null;
@@ -95,11 +97,15 @@ export type AnnotationScoreSchemaType = z.infer<
typeof AnnotationScoreDataSchema
>;
+export type AnnotationScoreDataType = ScoreConfigDataType;
+export const ANNOTATION_SCORE_DATA_TYPES_ARRAY =
+ Object.values(ScoreConfigDataType);
+
export type ScoreColumn = {
key: string;
name: string;
source: ScoreSourceType;
- dataType: ScoreDataTypeType;
+ dataType: AggregatableScoreDataType;
};
export type ScoreConfigSelection =
@@ -123,7 +129,7 @@ export type AnnotationScoreFormData = {
id: string | null;
configId: string;
name: string;
- dataType: ScoreDataTypeType;
+ dataType: AnnotationScoreDataType;
value?: number | null;
stringValue?: string | null;
comment?: string | null;
diff --git a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
index 6c1c9f446e..621558a073 100644
--- a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
+++ b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts
@@ -1,6 +1,9 @@
import { env } from "@/src/env.mjs";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
-import { filterAndValidateDbScoreList } from "@langfuse/shared";
+import {
+ AGGREGATABLE_SCORE_TYPES,
+ filterAndValidateDbScoreList,
+} from "@langfuse/shared";
import {
getObservationsTableWithModelData,
getObservationsWithModelDataFromEventsTable,
@@ -40,6 +43,7 @@ export async function getAllGenerations({
const validatedScores = filterAndValidateDbScoreList({
scores,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
includeHasMetadata: true,
onParseError: traceException,
});
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index b846db6198..69bd03a847 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -560,6 +560,7 @@ export const scoresRouter = createTRPCRouter({
authorUserId: ctx.session.user.id,
queueId: input.queueId ?? null,
timestamp,
+ longStringValue: "",
};
if (isNumericDataType(baseScore.dataType)) {
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index 01d71bdfed..f55a2ece3a 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -16,6 +16,8 @@ import {
singleFilter,
timeFilter,
type SessionOptions,
+ type ScoreDomain,
+ AGGREGATABLE_SCORE_TYPES,
} from "@langfuse/shared";
import { Prisma } from "@langfuse/shared/src/db";
import { TRPCError } from "@trpc/server";
@@ -108,6 +110,7 @@ const handleGetSessionById = async (input: {
const validatedScores = filterAndValidateDbScoreList({
scores,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
onParseError: traceException,
});
@@ -272,6 +275,7 @@ export const sessionRouter = createTRPCRouter({
const validatedScores = filterAndValidateDbScoreList({
scores,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
onParseError: traceException,
});
@@ -392,8 +396,9 @@ export const sessionRouter = createTRPCRouter({
}),
]);
- const validatedScores = filterAndValidateDbScoreList({
+ const validatedScores: ScoreDomain[] = filterAndValidateDbScoreList({
scores,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
onParseError: traceException,
});
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index f10ffed9c3..d5525112ed 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -20,6 +20,8 @@ import {
timeFilter,
type Observation,
TracingSearchType,
+ type ScoreDomain,
+ AGGREGATABLE_SCORE_TYPES,
} from "@langfuse/shared";
import {
traceException,
@@ -219,7 +221,7 @@ export const traceRouter = createTRPCRouter({
],
});
- const scores = await getScoresForTraces({
+ const traceScores = await getScoresForTraces({
projectId: ctx.session.projectId,
traceIds: res.map((r) => r.id),
limit: 1000,
@@ -229,7 +231,8 @@ export const traceRouter = createTRPCRouter({
});
const validatedScores = filterAndValidateDbScoreList({
- scores,
+ scores: traceScores,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
includeHasMetadata: true,
onParseError: traceException,
});
@@ -341,7 +344,7 @@ export const traceRouter = createTRPCRouter({
});
}
- const [observations, scores] = await Promise.all([
+ const [observations, traceScores] = await Promise.all([
getObservationsForTrace({
traceId: input.traceId,
projectId: input.projectId,
@@ -356,7 +359,8 @@ export const traceRouter = createTRPCRouter({
]);
const validatedScores = filterAndValidateDbScoreList({
- scores,
+ scores: traceScores,
+ dataTypes: AGGREGATABLE_SCORE_TYPES,
onParseError: traceException,
});
@@ -378,11 +382,14 @@ export const traceRouter = createTRPCRouter({
: undefined
: undefined;
+ const scores =
+ toDomainArrayWithStringifiedMetadata<ScoreDomain>(validatedScores);
+
return {
...toDomainWithStringifiedMetadata(ctx.trace),
input: ctx.trace.input ? JSON.stringify(ctx.trace.input) : null,
output: ctx.trace.output ? JSON.stringify(ctx.trace.output) : null,
- scores: toDomainArrayWithStringifiedMetadata(validatedScores),
+ scores,
latency: latencyMs !== undefined ? latencyMs / 1000 : undefined,
observations: observations.map((o) => ({
...toDomainWithStringifiedMetadata(o),
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 2f4c434f8f..98c98bb822 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -604,6 +604,7 @@ export class IngestionService {
? convertJsonSchemaToRecord(scoreEvent.body.metadata)
: {},
string_value: validatedScore.stringValue,
+ long_string_value: validatedScore.longStringValue,
execution_trace_id: validatedScore.executionTraceId,
queue_id: validatedScore.queueId ?? null,
created_at: Date.now(),