Skip to content

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

feat(scores): make `TEXT` scores available via public API (#12937)

Tobias Wochinger6603be67118e
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index 1ce3fbd25d..b3223326f7 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -431,6 +431,12 @@ types:
stringValue:
type: string
docs: The string representation of the score value. If no config is linked, can be any string. Otherwise, must map to a config category
+ TextScoreV1:
+ extends: BaseScoreV1
+ properties:
+ stringValue:
+ type: string
+ docs: The text content of the score (1-500 characters)
ScoreV1:
discriminant: "dataType"
union:
@@ -443,6 +449,9 @@ types:
BOOLEAN:
type: BooleanScoreV1
docs: "Score with BOOLEAN data type"
+ TEXT:
+ type: TextScoreV1
+ docs: "Score with TEXT data type"
# Source: packages/shared/src/features/scores/interfaces/api/v2/schemas.ts - APIScoreSchemaV2
BaseScore:
@@ -516,6 +525,12 @@ types:
stringValue:
type: string
docs: The string representation of the correction content
+ TextScore:
+ extends: BaseScore
+ properties:
+ stringValue:
+ type: string
+ docs: The text content of the score (1-500 characters)
Score:
discriminant: "dataType"
union:
@@ -531,13 +546,16 @@ types:
CORRECTION:
type: CorrectionScore
docs: "Score with CORRECTION data type"
+ TEXT:
+ type: TextScore
+ docs: "Score with TEXT data type"
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 and text scores, and numeric for boolean and numeric scores
# Source: web/src/features/public-api/types/comments.ts - APIComment
Comment:
@@ -932,6 +950,7 @@ types:
- NUMERIC
- BOOLEAN
- CATEGORICAL
+ - TEXT
ScoreDataType:
enum:
@@ -939,6 +958,7 @@ types:
- BOOLEAN
- CATEGORICAL
- CORRECTION
+ - TEXT
errors:
Error:
diff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.yml
index c1b31b172e..2b033f6c10 100644
--- a/fern/apis/server/definition/ingestion.yml
+++ b/fern/apis/server/definition/ingestion.yml
@@ -287,7 +287,7 @@ types:
docs: The annotation queue referenced by the score. Indicates if score was initially created while processing annotation queue.
value:
type: commons.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)
+ docs: The value of the score. Must be passed as string for categorical and text scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false). Text score values must be between 1 and 500 characters.
comment: optional<string>
metadata: optional<unknown>
dataType:
diff --git a/fern/apis/server/definition/legacy/score-v1.yml b/fern/apis/server/definition/legacy/score-v1.yml
index 85796c0820..5cc5a18ac4 100644
--- a/fern/apis/server/definition/legacy/score-v1.yml
+++ b/fern/apis/server/definition/legacy/score-v1.yml
@@ -31,7 +31,7 @@ types:
name: string
value:
type: commons.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)
+ docs: The value of the score. Must be passed as string for categorical and text scores, and numeric for boolean and numeric scores. Boolean score values must equal either 1 or 0 (true or false). Text score values must be between 1 and 500 characters.
comment: optional<string>
metadata: optional<map<string, unknown>>
environment:
@@ -85,6 +85,11 @@ types:
dataType: "BOOLEAN"
configId: "1234-5678-90ab-cdef"
traceId: "cdef-1234-5678-90ab"
+ - value:
+ name: "feedback"
+ value: "Great explanation of the concept"
+ dataType: "TEXT"
+ traceId: "cdef-1234-5678-90ab"
CreateScoreResponse:
properties:
id:
diff --git a/fern/apis/server/definition/scores.yml b/fern/apis/server/definition/scores.yml
index 603214aeac..9dd954635b 100644
--- a/fern/apis/server/definition/scores.yml
+++ b/fern/apis/server/definition/scores.yml
@@ -130,6 +130,11 @@ types:
properties:
trace: optional<GetScoresResponseTraceData>
+ GetScoresResponseDataText:
+ extends: commons.TextScore
+ properties:
+ trace: optional<GetScoresResponseTraceData>
+
GetScoresResponseData:
discriminant: dataType
union:
@@ -137,6 +142,7 @@ types:
CATEGORICAL: GetScoresResponseDataCategorical
BOOLEAN: GetScoresResponseDataBoolean
CORRECTION: GetScoresResponseDataCorrection
+ TEXT: GetScoresResponseDataText
GetScoresResponse:
properties:
diff --git a/packages/shared/src/domain/scores.ts b/packages/shared/src/domain/scores.ts
index e93a42706a..da5f7ffea8 100644
--- a/packages/shared/src/domain/scores.ts
+++ b/packages/shared/src/domain/scores.ts
@@ -130,9 +130,12 @@ export type AggregatableScore = ScoresByDataTypes<
typeof AGGREGATABLE_SCORE_TYPES
>;
-export const LISTABLE_SCORE_TYPES = ScoreDataTypeArray.filter(
- (type) => type !== "CORRECTION",
-) satisfies readonly ScoreDataTypeType[];
+export const LISTABLE_SCORE_TYPES = [
+ "NUMERIC",
+ "BOOLEAN",
+ "CATEGORICAL",
+ "TEXT",
+] as const 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/scores/interfaces/api/shared.ts b/packages/shared/src/features/scores/interfaces/api/shared.ts
index 510b134a6f..5aecdc9060 100644
--- a/packages/shared/src/features/scores/interfaces/api/shared.ts
+++ b/packages/shared/src/features/scores/interfaces/api/shared.ts
@@ -6,6 +6,7 @@ import { PostScoreBodyFoundationSchema } from "../shared";
import {
ScoreDataTypeDomain,
ScoreSourceDomain,
+ TEXT_SCORE_MAX_LENGTH,
} from "../../../../domain/scores";
import { singleFilter } from "../../../../interfaces/filters";
import { InvalidRequestError } from "../../../../errors";
@@ -74,7 +75,6 @@ export const GetScoresQuery = z.object({
});
// POST /scores
-// Please note that the POST /scores endpoint supports all score types (trace, session, dataset run) across v1 and v2.
/**
* PostScoresBody is copied for the ingestion API as `ScoreBody`. Please copy any changes here in `packages/shared/src/features/ingestion/types.ts`
*/
@@ -104,6 +104,11 @@ export const PostScoresBody = applyScoreValidation(
dataType: z.literal("CORRECTION"),
configId: z.undefined().nullish(), // Cannot have config
}),
+ z.object({
+ value: z.string().min(1).max(TEXT_SCORE_MAX_LENGTH),
+ dataType: z.literal("TEXT"),
+ configId: z.string().nullish(),
+ }),
z.object({
value: z.union([z.string(), z.number()]),
dataType: z.undefined(),
diff --git a/packages/shared/src/features/scores/interfaces/api/v1/schemas.ts b/packages/shared/src/features/scores/interfaces/api/v1/schemas.ts
index f2f505ddb0..37d8e2b65e 100644
--- a/packages/shared/src/features/scores/interfaces/api/v1/schemas.ts
+++ b/packages/shared/src/features/scores/interfaces/api/v1/schemas.ts
@@ -9,7 +9,7 @@ import {
/**
* Foundation schema for scores API v1 i.e. trace and observation scores ONLY
*
- * Must be extended with score data specific schema (numeric, categorical, boolean)
+ * Must be extended with score data specific schema (numeric, categorical, boolean, text)
* @see {@link NumericData}, {@link CategoricalData}, {@link BooleanData}
*/
const ScoreFoundationSchemaV1 = ScoreSchemaExclReferencesAndDates.extend({
@@ -22,8 +22,17 @@ const ScoreFoundationSchemaV1 = ScoreSchemaExclReferencesAndDates.extend({
observationId: z.string().nullish(),
});
-export const APIScoreSchemaV1 = ScoreFoundationSchemaV1.and(
- z.discriminatedUnion("dataType", [NumericData, CategoricalData, BooleanData]),
-);
+// Response-only schema without input validation constraints (e.g. length limits)
+const TextData = z.object({
+ stringValue: z.string(),
+ dataType: z.literal("TEXT"),
+});
+
+export const APIScoreSchemaV1 = z.discriminatedUnion("dataType", [
+ ScoreFoundationSchemaV1.extend(NumericData.shape),
+ ScoreFoundationSchemaV1.extend(CategoricalData.shape),
+ ScoreFoundationSchemaV1.extend(BooleanData.shape),
+ ScoreFoundationSchemaV1.omit({ value: true }).extend(TextData.shape),
+]);
export type APIScoreV1 = z.infer<typeof APIScoreSchemaV1>;
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 41b5994f6b..e60c79f831 100644
--- a/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts
+++ b/packages/shared/src/features/scores/interfaces/api/v2/schemas.ts
@@ -6,11 +6,18 @@ import {
} from "../../../../../domain";
import z from "zod";
+// Response-only schemas without input validation constraints (e.g. length limits).
+// Input constraints are enforced at write time; response schemas must accept any stored value.
const CorrectionData = z.object({
stringValue: z.string(),
dataType: z.literal("CORRECTION"),
});
+const TextData = z.object({
+ stringValue: z.string(),
+ dataType: z.literal("TEXT"),
+});
+
/**
* Foundation schema for scores API v2 i.e. trace, observation AND session scores
*
@@ -29,13 +36,13 @@ const ScoreFoundationSchemaV2 = ScoreSchemaExclReferencesAndDates.extend({
datasetRunId: z.string().nullish(),
});
-export const APIScoreSchemaV2 = ScoreFoundationSchemaV2.and(
- z.discriminatedUnion("dataType", [
- NumericData,
- CategoricalData,
- BooleanData,
- CorrectionData,
- ]),
-);
+export const APIScoreSchemaV2 = z.discriminatedUnion("dataType", [
+ ScoreFoundationSchemaV2.extend(NumericData.shape),
+ ScoreFoundationSchemaV2.extend(CategoricalData.shape),
+ ScoreFoundationSchemaV2.extend(BooleanData.shape),
+ ScoreFoundationSchemaV2.extend(CorrectionData.shape),
+ // a numeric value does not make sense for TEXT scores, so we omit the property
+ ScoreFoundationSchemaV2.omit({ value: true }).extend(TextData.shape),
+]);
export type APIScoreV2 = z.infer<typeof APIScoreSchemaV2>;
diff --git a/packages/shared/src/features/scores/interfaces/ingestion/validation.ts b/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
index 2ff685cae1..737992e79a 100644
--- a/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
+++ b/packages/shared/src/features/scores/interfaces/ingestion/validation.ts
@@ -7,31 +7,37 @@ import { TEXT_SCORE_MAX_LENGTH } from "../../../../domain/scores";
export const ScoreBodyWithoutConfig = applyScoreValidation(
z.discriminatedUnion("dataType", [
- PostScoreBodyFoundationSchema.merge(
+ PostScoreBodyFoundationSchema.extend(
z.object({
value: z.number(),
dataType: z.literal("NUMERIC"),
- }),
+ }).shape,
),
- PostScoreBodyFoundationSchema.merge(
+ PostScoreBodyFoundationSchema.extend(
z.object({
value: z.string(),
dataType: z.literal("CATEGORICAL"),
- }),
+ }).shape,
),
- PostScoreBodyFoundationSchema.merge(
+ PostScoreBodyFoundationSchema.extend(
z.object({
value: z.string(),
dataType: z.literal("CORRECTION"),
- }),
+ }).shape,
),
- PostScoreBodyFoundationSchema.merge(
+ PostScoreBodyFoundationSchema.extend(
z.object({
value: z.number().refine((val) => val === 0 || val === 1, {
message: "Value must be either 0 or 1",
}),
dataType: z.literal("BOOLEAN"),
- }),
+ }).shape,
+ ),
+ PostScoreBodyFoundationSchema.extend(
+ z.object({
+ value: z.string().min(1).max(TEXT_SCORE_MAX_LENGTH),
+ dataType: z.literal("TEXT"),
+ }).shape,
),
]),
);
diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.ts
index de3f561a91..132c60623a 100644
--- a/packages/shared/src/server/ingestion/types.ts
+++ b/packages/shared/src/server/ingestion/types.ts
@@ -4,6 +4,7 @@ import { z } from "zod";
import { NonEmptyString, jsonSchema } from "../../utils/zod";
import { ModelUsageUnit } from "../../constants";
import { ScoreSourceType } from "../../domain";
+import { TEXT_SCORE_MAX_LENGTH } from "../../domain/scores";
import { applyScoreValidation } from "../../utils/scores";
export const idSchema = z
@@ -526,21 +527,21 @@ const createAllIngestionSchemas = ({
const ScoreBody = applyScoreValidation(
z.discriminatedUnion("dataType", [
- BaseScoreBody.merge(
+ BaseScoreBody.extend(
z.object({
value: z.number(),
dataType: z.literal("NUMERIC"),
configId: z.string().nullish(),
- }),
+ }).shape,
),
- BaseScoreBody.merge(
+ BaseScoreBody.extend(
z.object({
value: z.string(),
dataType: z.literal("CATEGORICAL"),
configId: z.string().nullish(),
- }),
+ }).shape,
),
- BaseScoreBody.merge(
+ BaseScoreBody.extend(
z.object({
value: z.number().refine((value) => value === 0 || value === 1, {
message:
@@ -548,21 +549,28 @@ const createAllIngestionSchemas = ({
}),
dataType: z.literal("BOOLEAN"),
configId: z.string().nullish(),
- }),
+ }).shape,
),
- BaseScoreBody.merge(
+ BaseScoreBody.extend(
z.object({
value: z.string(),
dataType: z.literal("CORRECTION"),
configId: z.undefined().nullish(), // Cannot have config
- }),
+ }).shape,
),
- BaseScoreBody.merge(
+ BaseScoreBody.extend(
+ z.object({
+ value: z.string().min(1).max(TEXT_SCORE_MAX_LENGTH),
+ dataType: z.literal("TEXT"),
+ configId: z.string().nullish(),
+ }).shape,
+ ),
+ BaseScoreBody.extend(
z.object({
value: z.union([z.string(), z.number()]),
dataType: z.undefined(),
configId: z.string().nullish(),
- }),
+ }).shape,
),
]),
);
diff --git a/packages/shared/src/server/ingestion/validateAndInflateScore.ts b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
index 788d540507..9398403fbc 100644
--- a/packages/shared/src/server/ingestion/validateAndInflateScore.ts
+++ b/packages/shared/src/server/ingestion/validateAndInflateScore.ts
@@ -64,7 +64,7 @@ export async function validateAndInflateScore(
if (!validation.success) {
throw new InvalidRequestError(
- `Ingested score value type not valid against provided data type. Provide numeric values for numeric and boolean scores, and string values for categorical scores.`,
+ `Ingested score value type not valid against provided data type. Provide numeric values for numeric and boolean scores, string values for categorical scores, and string values of 1-500 characters for text scores.`,
);
}
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index d49544007d..9b1b4fa3e2 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -6353,6 +6353,12 @@ components:
description: >-
Custom start date for exports (required when exportMode is
FROM_CUSTOM_DATE)
+ compressed:
+ type: boolean
+ nullable: true
+ description: >-
+ Enable gzip compression for exported files (.csv.gz, .json.gz,
+ .jsonl.gz). Defaults to true.
required:
- projectId
- type
@@ -6399,6 +6405,8 @@ components:
type: string
format: date-time
nullable: true
+ compressed:
+ type: boolean
nextSyncAt:
type: string
format: date-time
@@ -6432,6 +6440,7 @@ components:
- forcePathStyle
- fileType
- exportMode
+ - compressed
- createdAt
- updatedAt
BlobStorageIntegrationsResponse:
@@ -7283,6 +7292,17 @@ components:
- stringValue
allOf:
- $ref: '#/components/schemas/BaseScoreV1'
+ TextScoreV1:
+ title: TextScoreV1
+ type: object
+ properties:
+ stringValue:
+ type: string
+ description: The text content of the score (1-500 characters)
+ required:
+ - stringValue
+ allOf:
+ - $ref: '#/components/schemas/BaseScoreV1'
ScoreV1:
title: ScoreV1
oneOf:
@@ -7319,6 +7339,17 @@ components:
- $ref: '#/components/schemas/BooleanScoreV1'
required:
- dataType
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ dataType:
+ type: string
+ enum:
+ - TEXT
+ - $ref: '#/components/schemas/TextScoreV1'
+ required:
+ - dataType
BaseScore:
title: BaseScore
type: object
@@ -7460,6 +7491,17 @@ components:
- stringValue
allOf:
- $ref: '#/components/schemas/BaseScore'
+ TextScore:
+ title: TextScore
+ type: object
+ properties:
+ stringValue:
+ type: string
+ description: The text content of the score (1-500 characters)
+ required:
+ - stringValue
+ allOf:
+ - $ref: '#/components/schemas/BaseScore'
Score:
title: Score
oneOf:
@@ -7507,6 +7549,17 @@ components:
- $ref: '#/components/schemas/CorrectionScore'
required:
- dataType
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ dataType:
+ type: string
+ enum:
+ - TEXT
+ - $ref: '#/components/schemas/TextScore'
+ required:
+ - dataType
CreateScoreValue:
title: CreateScoreValue
oneOf:
@@ -7514,8 +7567,8 @@ components:
format: double
- type: string
description: >-
- The value of the score. Must be passed as string for categorical scores,
- and numeric for boolean and numeric scores
+ The value of the score. Must be passed as string for categorical and
+ text scores, and numeric for boolean and numeric scores
Comment:
title: Comment
type: object
@@ -8235,6 +8288,7 @@ components:
- NUMERIC
- BOOLEAN
- CATEGORICAL
+ - TEXT
ScoreDataType:
title: ScoreDataType
type: string
@@ -8243,6 +8297,7 @@ components:
- BOOLEAN
- CATEGORICAL
- CORRECTION
+ - TEXT
DeleteDatasetItemResponse:
title: DeleteDatasetItemResponse
type: object
@@ -8869,9 +8924,10 @@ components:
value:
$ref: '#/components/schemas/CreateScoreValue'
description: >-
- 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)
+ The value of the score. Must be passed as string for categorical and
+ text scores, and numeric for boolean and numeric scores. Boolean
+ score values must equal either 1 or 0 (true or false). Text score
+ values must be between 1 and 500 characters.
comment:
type: string
nullable: true
@@ -9188,9 +9244,10 @@ components:
value:
$ref: '#/components/schemas/CreateScoreValue'
description: >-
- 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)
+ The value of the score. Must be passed as string for categorical and
+ text scores, and numeric for boolean and numeric scores. Boolean
+ score values must equal either 1 or 0 (true or false). Text score
+ values must be between 1 and 500 characters.
comment:
type: string
nullable: true
@@ -10821,6 +10878,15 @@ components:
nullable: true
allOf:
- $ref: '#/components/schemas/CorrectionScore'
+ GetScoresResponseDataText:
+ title: GetScoresResponseDataText
+ type: object
+ properties:
+ trace:
+ $ref: '#/components/schemas/GetScoresResponseTraceData'
+ nullable: true
+ allOf:
+ - $ref: '#/components/schemas/TextScore'
GetScoresResponseData:
title: GetScoresResponseData
oneOf:
@@ -10868,6 +10934,17 @@ components:
- $ref: '#/components/schemas/GetScoresResponseDataCorrection'
required:
- dataType
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ dataType:
+ type: string
+ enum:
+ - TEXT
+ - $ref: '#/components/schemas/GetScoresResponseDataText'
+ required:
+ - dataType
GetScoresResponse:
title: GetScoresResponse
type: object
diff --git a/web/src/__tests__/server/score-configs.servertest.ts b/web/src/__tests__/server/score-configs.servertest.ts
index f3b3314c97..5f03d22eb4 100644
--- a/web/src/__tests__/server/score-configs.servertest.ts
+++ b/web/src/__tests__/server/score-configs.servertest.ts
@@ -257,6 +257,34 @@ describe("/api/public/score-configs API Endpoint", () => {
]);
});
+ it("should POST a text score config", async () => {
+ const postScoreConfig = await makeZodVerifiedAPICall(
+ PostScoreConfigResponse,
+ "POST",
+ "/api/public/score-configs",
+ {
+ name: "text-config-name",
+ dataType: "TEXT",
+ },
+ auth,
+ );
+
+ const scoreConfig = await makeZodVerifiedAPICall(
+ GetScoreConfigResponse,
+ "GET",
+ `/api/public/score-configs/${postScoreConfig.body.id}`,
+ undefined,
+ auth,
+ );
+
+ expect(postScoreConfig.status).toBe(200);
+ expect(scoreConfig.body.name).toBe("text-config-name");
+ expect(scoreConfig.body.dataType).toBe("TEXT");
+ expect(scoreConfig.body.categories).toBeFalsy();
+ expect(scoreConfig.body.maxValue).toBeFalsy();
+ expect(scoreConfig.body.minValue).toBeFalsy();
+ });
+
it("should fail POST of numeric score config with invalid range", async () => {
try {
await makeZodVerifiedAPICall(
diff --git a/web/src/__tests__/server/scores-api-v1.servertest.ts b/web/src/__tests__/server/scores-api-v1.servertest.ts
index 691a44e4df..4b7c9ee2e3 100644
--- a/web/src/__tests__/server/scores-api-v1.servertest.ts
+++ b/web/src/__tests__/server/scores-api-v1.servertest.ts
@@ -75,6 +75,51 @@ describe("/api/public/scores API Endpoint", () => {
});
});
+ it("should GET a text score", async () => {
+ const { projectId, auth } = await createOrgProjectAndApiKey();
+
+ const scoreId = v4();
+ const traceId = v4();
+ const score = createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ trace_id: traceId,
+ name: "Text Score",
+ timestamp: Date.now(),
+ value: 0,
+ string_value: "Great explanation",
+ source: "API",
+ comment: "comment",
+ data_type: "TEXT" as const,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ is_deleted: 0,
+ });
+
+ await createScoresCh([score]);
+
+ const getScore = await makeZodVerifiedAPICall(
+ GetScoreResponseV1,
+ "GET",
+ `/api/public/scores/${scoreId}`,
+ undefined,
+ auth,
+ );
+
+ expect(getScore.status).toBe(200);
+ expect(getScore.body).toMatchObject({
+ id: scoreId,
+ name: "Text Score",
+ stringValue: "Great explanation",
+ comment: "comment",
+ source: "API",
+ traceId,
+ dataType: "TEXT",
+ });
+ expect(getScore.body).not.toHaveProperty("value");
+ });
+
it("should GET score with minimal score data and minimal trace data", async () => {
const { projectId, auth } = await createOrgProjectAndApiKey();
@@ -422,6 +467,8 @@ describe("/api/public/scores API Endpoint", () => {
const scoreId_5 = v4();
const scoreId_6 = v4();
const scoreId_7 = v4();
+ const textScoreId_1 = v4();
+ const textScoreId_2 = v4();
let authentication: string;
let newProjectId: string;
@@ -530,6 +577,26 @@ describe("/api/public/scores API Endpoint", () => {
environment: "production",
});
+ const textScore1 = createTraceScore({
+ id: textScoreId_1,
+ project_id: newProjectId,
+ trace_id: traceId_2,
+ name: "text-score-name",
+ data_type: "TEXT",
+ string_value: "text-value-1",
+ value: 0,
+ });
+
+ const textScore2 = createTraceScore({
+ id: textScoreId_2,
+ project_id: newProjectId,
+ trace_id: traceId_3,
+ name: "text-score-name",
+ data_type: "TEXT",
+ string_value: "text-value-2",
+ value: 0,
+ });
+
const sessionScore1 = createSessionScore({
id: scoreId_6,
project_id: newProjectId,
@@ -554,6 +621,8 @@ describe("/api/public/scores API Endpoint", () => {
score3,
score4,
score5,
+ textScore1,
+ textScore2,
sessionScore1,
sessionScore2,
]);
@@ -571,7 +640,7 @@ describe("/api/public/scores API Endpoint", () => {
expect(getAllScore.body.meta).toMatchObject({
page: 1,
limit: 50,
- totalItems: 5, // 7 scores in total, but only 5 are trace scores
+ totalItems: 7, // 9 scores in total, but only 7 are trace scores
totalPages: 1,
});
for (const val of getAllScore.body.data) {
@@ -631,6 +700,31 @@ describe("/api/public/scores API Endpoint", () => {
}
});
+ it("get all scores for text data type", async () => {
+ const getAllScore = await makeZodVerifiedAPICall(
+ GetScoresResponseV1,
+ "GET",
+ `/api/public/scores?dataType=TEXT`,
+ 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: "TEXT",
+ name: "text-score-name",
+ });
+ expect(val.stringValue).toContain("text-value");
+ }
+ });
+
it("get all scores for trace tag 'prod'", async () => {
const getAllScore = await makeZodVerifiedAPICall(
GetScoresResponseV1,
@@ -696,7 +790,7 @@ describe("/api/public/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/__tests__/server/scores-api-v2.servertest.ts b/web/src/__tests__/server/scores-api-v2.servertest.ts
index 67e498f202..4de05a2854 100644
--- a/web/src/__tests__/server/scores-api-v2.servertest.ts
+++ b/web/src/__tests__/server/scores-api-v2.servertest.ts
@@ -190,6 +190,51 @@ describe("/api/public/v2/scores API Endpoint", () => {
dataType: "NUMERIC",
});
});
+
+ it("should GET a text score", async () => {
+ const { projectId, auth } = await createOrgProjectAndApiKey();
+
+ const scoreId = v4();
+ const traceId = v4();
+ const score = createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ trace_id: traceId,
+ name: "Text Score",
+ timestamp: Date.now(),
+ value: 0,
+ string_value: "Great explanation",
+ source: "API",
+ comment: "comment",
+ data_type: "TEXT" as const,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ is_deleted: 0,
+ });
+
+ await createScoresCh([score]);
+
+ const getScore = await makeZodVerifiedAPICall(
+ GetScoreResponseV2,
+ "GET",
+ `/api/public/v2/scores/${scoreId}`,
+ undefined,
+ auth,
+ );
+
+ expect(getScore.status).toBe(200);
+ expect(getScore.body).toMatchObject({
+ id: scoreId,
+ name: "Text Score",
+ stringValue: "Great explanation",
+ comment: "comment",
+ source: "API",
+ traceId,
+ dataType: "TEXT",
+ });
+ expect(getScore.body).not.toHaveProperty("value");
+ });
});
describe("GET /api/public/scores", () => {
@@ -217,6 +262,8 @@ describe("/api/public/v2/scores API Endpoint", () => {
const scoreId_9 = v4();
const correctionScoreId_1 = v4();
const correctionScoreId_2 = v4();
+ const textScoreId_1 = v4();
+ const textScoreId_2 = v4();
let authentication: string;
let newProjectId: string;
let executionTraceId: string;
@@ -348,6 +395,26 @@ describe("/api/public/v2/scores API Endpoint", () => {
environment: "annotation",
});
+ const textScore1 = createTraceScore({
+ id: textScoreId_1,
+ project_id: newProjectId,
+ trace_id: traceId_2,
+ name: "text-score-name",
+ data_type: "TEXT",
+ string_value: "text-value-1",
+ value: 0,
+ });
+
+ const textScore2 = createTraceScore({
+ id: textScoreId_2,
+ project_id: newProjectId,
+ trace_id: traceId_3,
+ name: "text-score-name",
+ data_type: "TEXT",
+ string_value: "text-value-2",
+ value: 0,
+ });
+
const sessionScore1 = createSessionScore({
id: scoreId_6,
project_id: newProjectId,
@@ -396,6 +463,8 @@ describe("/api/public/v2/scores API Endpoint", () => {
runScore2,
correction1,
correction2,
+ textScore1,
+ textScore2,
]);
});
@@ -411,7 +480,7 @@ describe("/api/public/v2/scores API Endpoint", () => {
expect(getAllScore.body.meta).toMatchObject({
page: 1,
limit: 50,
- totalItems: 11,
+ totalItems: 13,
totalPages: 1,
});
for (const val of getAllScore.body.data) {
@@ -517,6 +586,31 @@ describe("/api/public/v2/scores API Endpoint", () => {
}
});
+ it("get all scores for text data type", async () => {
+ const getAllScore = await makeZodVerifiedAPICall(
+ GetScoresResponseV2,
+ "GET",
+ `/api/public/v2/scores?dataType=TEXT`,
+ 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: "TEXT",
+ name: "text-score-name",
+ });
+ expect(val.stringValue).toContain("text-value");
+ }
+ });
+
it("get all scores for trace tag 'prod'", async () => {
const getAllScore = await makeZodVerifiedAPICall(
GetScoresResponseV2,
@@ -737,7 +831,7 @@ describe("/api/public/v2/scores API Endpoint", () => {
expect(getAllScore.body.meta).toMatchObject({
page: 1,
limit: 50,
- totalItems: 2,
+ totalItems: 3,
totalPages: 1,
});
for (const val of getAllScore.body.data) {
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index d4ff42510a..b381ab8912 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -264,7 +264,7 @@ export default function ScoresTable({
count: n.count !== undefined ? Number(n.count) : undefined,
})) ?? undefined,
source: ["ANNOTATION", "API", "EVAL"],
- dataType: LISTABLE_SCORE_TYPES,
+ dataType: [...LISTABLE_SCORE_TYPES],
value: [],
stringValue:
filterOptions.data?.stringValue?.map((sv) => ({
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 9f25d391ce..572f4be0b0 100644
--- a/web/src/features/public-api/server/scores-api-service.ts
+++ b/web/src/features/public-api/server/scores-api-service.ts
@@ -4,10 +4,7 @@ import {
convertScoreToPublicApi,
type ScoreQueryType,
} from "@/src/features/public-api/server/scores";
-import {
- AGGREGATABLE_SCORE_TYPES,
- type ScoreSourceType,
-} from "@langfuse/shared";
+import { LISTABLE_SCORE_TYPES, type ScoreSourceType } from "@langfuse/shared";
import { _handleGetScoreById } from "@langfuse/shared/src/server";
export class ScoresApiService {
@@ -15,8 +12,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
+ * v1: Returns listable scores (NUMERIC, BOOLEAN, CATEGORICAL, TEXT) - excludes CORRECTION
+ * v2: Returns all score types including CORRECTION and TEXT
*/
async getScoreById({
projectId,
@@ -33,7 +30,7 @@ export class ScoresApiService {
source,
scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",
scoreDataTypes:
- this.apiVersion === "v1" ? AGGREGATABLE_SCORE_TYPES : undefined,
+ this.apiVersion === "v1" ? LISTABLE_SCORE_TYPES : undefined,
preferredClickhouseService: "ReadOnly",
});
@@ -46,29 +43,29 @@ export class ScoresApiService {
/**
* 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
+ * v1: Returns listable scores (NUMERIC, BOOLEAN, CATEGORICAL, TEXT) - excludes CORRECTION
+ * v2: Returns all score types including CORRECTION and TEXT
*/
async generateScoresForPublicApi(props: ScoreQueryType) {
return _handleGenerateScoresForPublicApi({
props,
scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",
scoreDataTypes:
- this.apiVersion === "v1" ? AGGREGATABLE_SCORE_TYPES : undefined,
+ this.apiVersion === "v1" ? LISTABLE_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
+ * v1: Only counts listable scores (NUMERIC, BOOLEAN, CATEGORICAL, TEXT) - excludes CORRECTION
+ * v2: Counts all score types including CORRECTION and TEXT
*/
async getScoresCountForPublicApi(props: ScoreQueryType) {
return _handleGetScoresCountForPublicApi({
props,
scoreScope: this.apiVersion === "v1" ? "traces_only" : "all",
scoreDataTypes:
- this.apiVersion === "v1" ? AGGREGATABLE_SCORE_TYPES : undefined,
+ this.apiVersion === "v1" ? LISTABLE_SCORE_TYPES : undefined,
});
}
}
diff --git a/web/src/features/public-api/server/scores.ts b/web/src/features/public-api/server/scores.ts
index 1601edbb75..dcdf191587 100644
--- a/web/src/features/public-api/server/scores.ts
+++ b/web/src/features/public-api/server/scores.ts
@@ -18,14 +18,26 @@ import {
type FilterState,
} from "@langfuse/shared";
+type ScoreApiResult = Omit<ScoreDomain, "longStringValue"> & {
+ stringValue?: string | null;
+};
+type TextScoreApiResult = Omit<ScoreDomain, "longStringValue" | "value"> & {
+ stringValue?: string | null;
+};
+
/**
* Converts a ScoreDomain object to API format.
* For CORRECTION scores, moves longStringValue to stringValue for API compatibility.
+ * For TEXT scores, removes longStringValue and value (always 0, not meaningful).
* For other score types, removes longStringValue.
*/
-export const convertScoreToPublicApi = <T extends ScoreDomain>(
- score: T,
-): Omit<T, "longStringValue"> & { stringValue?: string | null } => {
+export function convertScoreToPublicApi(
+ score: ScoreDomain & { dataType: "TEXT" },
+): TextScoreApiResult;
+export function convertScoreToPublicApi(score: ScoreDomain): ScoreApiResult;
+export function convertScoreToPublicApi(
+ score: ScoreDomain,
+): ScoreApiResult | TextScoreApiResult {
if (score.dataType === ScoreDataTypeEnum.CORRECTION) {
const { longStringValue, ...rest } = score;
return {
@@ -34,8 +46,12 @@ export const convertScoreToPublicApi = <T extends ScoreDomain>(
};
}
+ if (score.dataType === ScoreDataTypeEnum.TEXT) {
+ return removeObjectKeys(score, ["longStringValue", "value"]);
+ }
+
return removeObjectKeys(score, ["longStringValue"]);
-};
+}
export type ScoreQueryType = {
page: number;
diff --git a/web/src/features/public-api/types/score-configs.ts b/web/src/features/public-api/types/score-configs.ts
index f4940c3bcc..d74f73daad 100644
--- a/web/src/features/public-api/types/score-configs.ts
+++ b/web/src/features/public-api/types/score-configs.ts
@@ -97,6 +97,15 @@ export const PostScoreConfigBody = z
categories: z.undefined(),
}).shape,
}),
+ z.object({
+ ...PostScoreConfigBase.shape,
+ ...z.object({
+ dataType: z.literal("TEXT"),
+ categories: z.undefined(),
+ maxValue: z.undefined().nullish(),
+ minValue: z.undefined().nullish(),
+ }).shape,
+ }),
])
.superRefine(validateNumericRangeFields);
diff --git a/web/src/features/scores/components/AnnotationForm.tsx b/web/src/features/scores/components/AnnotationForm.tsx
index e4e1f4f9bc..28dedc81cd 100644
--- a/web/src/features/scores/components/AnnotationForm.tsx
+++ b/web/src/features/scores/components/AnnotationForm.tsx
@@ -297,10 +297,17 @@ function InnerAnnotationForm<Target extends ScoreTarget>({
form.setValue(`scoreData.${index}.stringValue`, previousScore.stringValue);
form.setValue(`scoreData.${index}.comment`, previousScore.comment);
form.setValue(`scoreData.${index}.timestamp`, previousScore.timestamp);
- form.setError(`scoreData.${index}.value`, {
- type: "server",
- message: "Failed to delete score",
- });
+ if (isTextDataType(field.dataType)) {
+ form.setError(`scoreData.${index}.stringValue`, {
+ type: "server",
+ message: "Failed to delete score",
+ });
+ } else {
+ form.setError(`scoreData.${index}.value`, {
+ type: "server",
+ message: "Failed to delete score",
+ });
+ }
};
const handleDeleteScore = (index: number) => {
@@ -316,7 +323,11 @@ function InnerAnnotationForm<Target extends ScoreTarget>({
};
// Optimistically clear form
- form.clearErrors(`scoreData.${index}.value`);
+ if (isTextDataType(field.dataType)) {
+ form.clearErrors(`scoreData.${index}.stringValue`);
+ } else {
+ form.clearErrors(`scoreData.${index}.value`);
+ }
update(index, {
name: field.name,
dataType: field.dataType,
@@ -351,10 +362,17 @@ function InnerAnnotationForm<Target extends ScoreTarget>({
) => {
form.setValue(`scoreData.${index}.value`, previousValue);
form.setValue(`scoreData.${index}.stringValue`, previousStringValue);
- form.setError(`scoreData.${index}.value`, {
- type: "server",
- message: "Failed to update score",
- });
+ if (isTextDataType(controlledFields[index]?.dataType)) {
+ form.setError(`scoreData.${index}.stringValue`, {
+ type: "server",
+ message: "Failed to update score",
+ });
+ } else {
+ form.setError(`scoreData.${index}.value`, {
+ type: "server",
+ message: "Failed to update score",
+ });
+ }
};
const rollbackCreateError = (
@@ -368,10 +386,17 @@ function InnerAnnotationForm<Target extends ScoreTarget>({
form.setValue(`scoreData.${index}.timestamp`, previousTimestamp);
form.setValue(`scoreData.${index}.value`, previousValue);
form.setValue(`scoreData.${index}.stringValue`, previousStringValue);
- form.setError(`scoreData.${index}.value`, {
- type: "server",
- message: "Failed to create score",
- });
+ if (isTextDataType(controlledFields[index]?.dataType)) {
+ form.setError(`scoreData.${index}.stringValue`, {
+ type: "server",
+ message: "Failed to create score",
+ });
+ } else {
+ form.setError(`scoreData.${index}.value`, {
+ type: "server",
+ message: "Failed to create score",
+ });
+ }
};
const handleUpsert = (
diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
index 20717c1e09..c8fc022f25 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts
@@ -624,6 +624,69 @@ describe("Ingestion end-to-end tests", () => {
}, 10_000);
});
+ it("should correctly ingest a TEXT score", async () => {
+ const traceId = randomUUID();
+ const scoreId = randomUUID();
+
+ const traceEventList: TraceEventType[] = [
+ {
+ type: "trace-create",
+ id: traceId,
+ timestamp: new Date().toISOString(),
+ body: {
+ name: "trace-for-text-score",
+ timestamp: new Date().toISOString(),
+ environment,
+ },
+ },
+ ];
+
+ const scoreEventList: ScoreEventType[] = [
+ {
+ id: randomUUID(),
+ type: "score-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: scoreId,
+ dataType: "TEXT",
+ name: "text-score",
+ value: "Great explanation of the concept",
+ source: ScoreSourceEnum.API,
+ traceId: traceId,
+ environment,
+ },
+ },
+ ];
+
+ await Promise.all([
+ ingestionService.processTraceEventList({
+ projectId,
+ entityId: traceId,
+ createdAtTimestamp: new Date(),
+ traceEventList,
+ }),
+ ingestionService.processScoreEventList({
+ projectId,
+ entityId: scoreId,
+ createdAtTimestamp: new Date(),
+ scoreEventList,
+ }),
+ ]);
+
+ await clickhouseWriter.flushAll(true);
+
+ const score = await getClickhouseRecord(TableName.Scores, scoreId);
+
+ expect(score.id).toBe(scoreId);
+ expect(score.trace_id).toBe(traceId);
+ expect(score.name).toBe("text-score");
+ expect(score.data_type).toBe("TEXT");
+ expect(score.string_value).toBe("Great explanation of the concept");
+ expect(score.value).toBe(0);
+ expect(score.source).toBe(ScoreSourceEnum.API);
+ expect(score.project_id).toBe(projectId);
+ }, 10_000);
+
[
{
observationExternalModel: "gpt-3.5",