Skip to content

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

feat(scores): add v3 scores API — polymorphic value, flag-gated (Phase 1) (#13995)

Niklas Semmler4134aabe35d0
diff --git a/.env.dev.example b/.env.dev.example
index fde0b877f6..cde73931cc 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -192,5 +192,7 @@ LANGFUSE_MIGRATION_V4_NATIVE_OTEL_BEHAVIOUR=dual_write
# Legacy tracing UI controls
LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH=false
+LANGFUSE_ENABLE_SCORES_V3_API=true
+
CLICKHOUSE_USE_LIGHTWEIGHT_UPDATE="true"
CLICKHOUSE_DISABLE_LAZY_MATERIALIZATION=true
diff --git a/.env.prod.example b/.env.prod.example
index 09e74927f6..7971b4f9b1 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -354,3 +354,7 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# LANGFUSE_INIT_ORG_CLOUD_PLAN=
### END Langfuse CI Config
+
+# v3 Scores API (preview, Cloud-only). Self-hosted instances should leave this
+# unset until the API graduates from preview.
+# LANGFUSE_ENABLE_SCORES_V3_API=false
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
index f39223f086..f4a22538d8 100644
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -386,6 +386,7 @@ jobs:
echo "ADMIN_API_KEY=admin-api-key" >> .env
echo "LANGFUSE_EE_LICENSE_KEY=langfuse_ee_test" >> .env
echo "LANGFUSE_SKIP_EVALUATOR_MODEL_CALL_VALIDATION=true" >> .env
+ echo "LANGFUSE_ENABLE_SCORES_V3_API=true" >> .env
- name: Setup Turbo cache
if: env.CI_CACHE_ALLOWED == 'true'
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # zizmor: ignore[cache-poisoning] test job cache only; publish jobs rebuild artifacts and do not restore this cache
diff --git a/fern/apis/server/_drafts/scores-v3.yml b/fern/apis/server/_drafts/scores-v3.yml
new file mode 100644
index 0000000000..99f994becf
--- /dev/null
+++ b/fern/apis/server/_drafts/scores-v3.yml
@@ -0,0 +1,105 @@
+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json
+imports:
+ commons: ../definition/commons.yml
+
+service:
+ auth: true
+ base-path: /api/public
+ endpoints:
+ getManyV3:
+ docs: |
+ Get a list of scores with a polymorphic `value` field (v3).
+
+ The `value` field type depends on `dataType`:
+ - `NUMERIC` → number
+ - `BOOLEAN` → boolean
+ - `CATEGORICAL`, `TEXT`, `CORRECTION` → string
+
+ Currently in preview for Langfuse Cloud v4 users; not yet available on
+ self-hosted Langfuse.
+ method: GET
+ path: /v3/scores
+ request:
+ name: GetScoresV3Request
+ query-parameters:
+ limit:
+ type: optional<integer>
+ docs: Number of items per page. Maximum 100, default 50. Requests with a limit greater than 100 return HTTP 400.
+ response: GetScoresV3Response
+
+types:
+ BaseScoreV3:
+ properties:
+ id: string
+ projectId: string
+ name: string
+ source: commons.ScoreSource
+ timestamp: datetime
+ environment:
+ type: string
+ docs: The environment from which this score originated.
+ createdAt: datetime
+ updatedAt: datetime
+
+ NumericScoreV3:
+ extends: BaseScoreV3
+ properties:
+ value:
+ type: double
+ docs: The numeric value of the score.
+
+ BooleanScoreV3:
+ extends: BaseScoreV3
+ properties:
+ value:
+ type: boolean
+ docs: The boolean value of the score.
+
+ CategoricalScoreV3:
+ extends: BaseScoreV3
+ properties:
+ value:
+ type: string
+ docs: The string category value of the score.
+
+ TextScoreV3:
+ extends: BaseScoreV3
+ properties:
+ value:
+ type: string
+ docs: The text content of the score.
+
+ CorrectionScoreV3:
+ extends: BaseScoreV3
+ properties:
+ value:
+ type: string
+ docs: The correction content of the score. Empty string if not set.
+
+ ScoreV3:
+ discriminant: dataType
+ union:
+ NUMERIC:
+ type: NumericScoreV3
+ docs: Score with NUMERIC data type. Value is a number.
+ BOOLEAN:
+ type: BooleanScoreV3
+ docs: Score with BOOLEAN data type. Value is a boolean.
+ CATEGORICAL:
+ type: CategoricalScoreV3
+ docs: Score with CATEGORICAL data type. Value is a string category.
+ TEXT:
+ type: TextScoreV3
+ docs: Score with TEXT data type. Value is a string.
+ CORRECTION:
+ type: CorrectionScoreV3
+ docs: Score with CORRECTION data type. Value is the correction string.
+
+ GetScoresV3Meta:
+ properties:
+ limit: integer
+
+ GetScoresV3Response:
+ properties:
+ data: list<ScoreV3>
+ meta: GetScoresV3Meta
diff --git a/packages/shared/src/features/scores/interfaces/api/index.ts b/packages/shared/src/features/scores/interfaces/api/index.ts
index 309d300206..474d7cb572 100644
--- a/packages/shared/src/features/scores/interfaces/api/index.ts
+++ b/packages/shared/src/features/scores/interfaces/api/index.ts
@@ -3,3 +3,6 @@ export * from "./v1/validation";
export * from "./v1/endpoints";
export * from "./v2/validation";
export * from "./v2/endpoints";
+export * from "./v3/schemas";
+export * from "./v3/endpoints";
+export * from "./v3/validation";
diff --git a/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts b/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts
new file mode 100644
index 0000000000..e3209fc37c
--- /dev/null
+++ b/packages/shared/src/features/scores/interfaces/api/v3/endpoints.ts
@@ -0,0 +1,14 @@
+import { z } from "zod";
+import { APIScoreSchemaV3 } from "./schemas";
+
+// GET /v3/scores
+export const GetScoresQueryV3 = z.object({
+ limit: z.coerce.number().int().positive().max(100).default(50),
+});
+
+export const GetScoresResponseV3 = z.object({
+ data: z.array(APIScoreSchemaV3),
+ meta: z.object({
+ limit: z.number(),
+ }),
+});
diff --git a/packages/shared/src/features/scores/interfaces/api/v3/schemas.ts b/packages/shared/src/features/scores/interfaces/api/v3/schemas.ts
new file mode 100644
index 0000000000..63a4e0bee3
--- /dev/null
+++ b/packages/shared/src/features/scores/interfaces/api/v3/schemas.ts
@@ -0,0 +1,47 @@
+import { z } from "zod";
+import { ScoreSourceDomain } from "../../../../../domain/scores";
+
+/**
+ * Foundation schema for scores API v3.
+ *
+ * Must be extended with a dataType-specific value shape.
+ *
+ * Unlike v1/v2, v3 returns the score's value as a single polymorphic field
+ * (number | boolean | string) rather than the dataType-split
+ * `value` / `stringValue` / `longStringValue` triple.
+ */
+const ScoreFoundationSchemaV3 = z.object({
+ id: z.string(),
+ projectId: z.string(),
+ name: z.string(),
+ source: ScoreSourceDomain,
+ timestamp: z.coerce.date(),
+ environment: z.string(),
+ createdAt: z.coerce.date(),
+ updatedAt: z.coerce.date(),
+});
+
+export const APIScoreSchemaV3 = z.discriminatedUnion("dataType", [
+ ScoreFoundationSchemaV3.extend({
+ dataType: z.literal("NUMERIC"),
+ value: z.number(),
+ }),
+ ScoreFoundationSchemaV3.extend({
+ dataType: z.literal("BOOLEAN"),
+ value: z.boolean(),
+ }),
+ ScoreFoundationSchemaV3.extend({
+ dataType: z.literal("CATEGORICAL"),
+ value: z.string(),
+ }),
+ ScoreFoundationSchemaV3.extend({
+ dataType: z.literal("TEXT"),
+ value: z.string(),
+ }),
+ ScoreFoundationSchemaV3.extend({
+ dataType: z.literal("CORRECTION"),
+ value: z.string(),
+ }),
+]);
+
+export type APIScoreV3 = z.infer<typeof APIScoreSchemaV3>;
diff --git a/packages/shared/src/features/scores/interfaces/api/v3/validation.ts b/packages/shared/src/features/scores/interfaces/api/v3/validation.ts
new file mode 100644
index 0000000000..9790ef7b45
--- /dev/null
+++ b/packages/shared/src/features/scores/interfaces/api/v3/validation.ts
@@ -0,0 +1,25 @@
+import z from "zod";
+import { APIScoreSchemaV3 } from "./schemas";
+
+/**
+ * Use this function when pulling a list of scores from the database before returning to the public API to ensure type safety.
+ * All scores are expected to pass the validation. If a score fails validation, it will be logged.
+ * @param scores
+ * @returns list of validated v3 scores
+ */
+export const filterAndValidateV3GetScoreList = (
+ scores: unknown[],
+ onParseError?: (error: z.ZodError) => void,
+): z.infer<typeof APIScoreSchemaV3>[] =>
+ scores.reduce(
+ (acc: z.infer<typeof APIScoreSchemaV3>[], ts) => {
+ const result = APIScoreSchemaV3.safeParse(ts);
+ if (result.success) {
+ acc.push(result.data);
+ } else {
+ onParseError?.(result.error);
+ }
+ return acc;
+ },
+ [] as z.infer<typeof APIScoreSchemaV3>[],
+ );
diff --git a/web/src/__tests__/server/scores-api-v3.servertest.ts b/web/src/__tests__/server/scores-api-v3.servertest.ts
new file mode 100644
index 0000000000..642af3ada0
--- /dev/null
+++ b/web/src/__tests__/server/scores-api-v3.servertest.ts
@@ -0,0 +1,152 @@
+import {
+ createTraceScore,
+ createScoresCh,
+ createOrgProjectAndApiKey,
+} from "@langfuse/shared/src/server";
+import {
+ makeAPICall,
+ makeZodVerifiedAPICall,
+} from "@/src/__tests__/test-utils";
+import { GetScoresResponseV3 } from "@langfuse/shared";
+import { v4 } from "uuid";
+
+describe("/api/public/v3/scores API Endpoint", () => {
+ describe("GET /api/public/v3/scores", () => {
+ let auth: string;
+ let projectId: string;
+
+ beforeAll(async () => {
+ const project = await createOrgProjectAndApiKey();
+ auth = project.auth;
+ projectId = project.projectId;
+ });
+
+ it("returns scores with default limit=50 and meta", async () => {
+ const scores = Array.from({ length: 3 }, () =>
+ createTraceScore({ project_id: projectId }),
+ );
+ await createScoresCh(scores);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores",
+ undefined,
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.meta).toMatchObject({ limit: 50 });
+ expect(res.body.meta).not.toHaveProperty("cursor");
+ expect(res.body.data.length).toBeGreaterThanOrEqual(3);
+ });
+
+ it("respects limit param", async () => {
+ const scores = Array.from({ length: 5 }, () =>
+ createTraceScore({ project_id: projectId }),
+ );
+ await createScoresCh(scores);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores?limit=2",
+ undefined,
+ auth,
+ );
+
+ expect(res.status).toBe(200);
+ expect(res.body.meta.limit).toBe(2);
+ expect(res.body.data.length).toBeLessThanOrEqual(2);
+ });
+
+ it.each([101, 0, -1, "abc"])("limit=%s → 400", async (limit) => {
+ const res = await makeAPICall(
+ "GET",
+ `/api/public/v3/scores?limit=${limit}`,
+ undefined,
+ auth,
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it.each([
+ ["NUMERIC", { value: 0.75, data_type: "NUMERIC" as const }, 0.75],
+ [
+ "BOOLEAN",
+ { value: 1, string_value: "true", data_type: "BOOLEAN" as const },
+ true,
+ ],
+ [
+ "CATEGORICAL",
+ {
+ value: 0,
+ string_value: "excellent",
+ data_type: "CATEGORICAL" as const,
+ },
+ "excellent",
+ ],
+ [
+ "TEXT",
+ {
+ value: 0,
+ string_value: "Very detailed feedback",
+ data_type: "TEXT" as const,
+ },
+ "Very detailed feedback",
+ ],
+ [
+ "CORRECTION",
+ {
+ value: 0,
+ long_string_value: "This is the corrected output",
+ data_type: "CORRECTION" as const,
+ },
+ "This is the corrected output",
+ ],
+ ])(
+ "%s score has correct polymorphic value",
+ async (_dataType, scoreFields, expected) => {
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({
+ id: scoreId,
+ project_id: projectId,
+ ...scoreFields,
+ }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores",
+ undefined,
+ auth,
+ );
+
+ const score = res.body.data.find((s) => s.id === scoreId);
+ expect(score).toBeDefined();
+ expect(score!.value).toBe(expected);
+ },
+ );
+
+ it("tenant isolation: project A cannot see project B scores", async () => {
+ const projectB = await createOrgProjectAndApiKey();
+ const scoreId = v4();
+ await createScoresCh([
+ createTraceScore({ id: scoreId, project_id: projectB.projectId }),
+ ]);
+
+ const res = await makeZodVerifiedAPICall(
+ GetScoresResponseV3,
+ "GET",
+ "/api/public/v3/scores",
+ undefined,
+ auth,
+ );
+
+ const leaked = res.body.data.find((s) => s.id === scoreId);
+ expect(leaked).toBeUndefined();
+ });
+ });
+});
diff --git a/web/src/__tests__/server/unit/polymorphicValue.servertest.ts b/web/src/__tests__/server/unit/polymorphicValue.servertest.ts
new file mode 100644
index 0000000000..ea1ab01b58
--- /dev/null
+++ b/web/src/__tests__/server/unit/polymorphicValue.servertest.ts
@@ -0,0 +1,36 @@
+import { polymorphicValue } from "@/src/features/public-api/server/scores-api-v3";
+
+describe("polymorphicValue", () => {
+ it.each([
+ [{ dataType: "NUMERIC" as const, value: 0.85 }, 0.85],
+ [{ dataType: "BOOLEAN" as const, value: 1, stringValue: "true" }, true],
+ [{ dataType: "BOOLEAN" as const, value: 0, stringValue: "false" }, false],
+ [
+ { dataType: "CATEGORICAL" as const, value: 0, stringValue: "good" },
+ "good",
+ ],
+ [
+ { dataType: "TEXT" as const, value: 0, stringValue: "Great explanation" },
+ "Great explanation",
+ ],
+ [
+ {
+ dataType: "CORRECTION" as const,
+ value: 0,
+ stringValue: null,
+ longStringValue: "corrected output",
+ },
+ "corrected output",
+ ],
+ ] as const)("returns expected value for %o", (input, expected) => {
+ expect(polymorphicValue(input)).toBe(expected);
+ });
+
+ it.each([
+ [{ dataType: "CATEGORICAL" as const, value: 0, stringValue: null }],
+
+ [{ dataType: "UNKNOWN" as any, value: 0 }],
+ ])("throws for invalid input %o", (input) => {
+ expect(() => polymorphicValue(input)).toThrow();
+ });
+});
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 43710ad279..f6ab607a82 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -437,6 +437,8 @@ export const env = createEnv({
.enum(["legacy", "dual", "events_only"])
.default("legacy"),
+ LANGFUSE_ENABLE_SCORES_V3_API: z.enum(["true", "false"]).default("false"),
+
// Blocked users for chat completion API (userId:reason format)
LANGFUSE_BLOCKED_USERIDS_CHATCOMPLETION: z
.string()
@@ -845,6 +847,7 @@ export const env = createEnv({
// Legacy tracing search controls
LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH:
process.env.LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH,
+ LANGFUSE_ENABLE_SCORES_V3_API: process.env.LANGFUSE_ENABLE_SCORES_V3_API,
LANGFUSE_BLOCKED_USERIDS_CHATCOMPLETION:
process.env.LANGFUSE_BLOCKED_USERIDS_CHATCOMPLETION,
},
diff --git a/web/src/features/public-api/server/scores-api-v3.ts b/web/src/features/public-api/server/scores-api-v3.ts
new file mode 100644
index 0000000000..79d1c154c0
--- /dev/null
+++ b/web/src/features/public-api/server/scores-api-v3.ts
@@ -0,0 +1,154 @@
+import {
+ convertClickhouseScoreToDomain,
+ logger,
+ measureAndReturn,
+ queryClickhouse,
+ type ScoreRecordReadType,
+} from "@langfuse/shared/src/server";
+import type {
+ APIScoreV3,
+ ScoreDataTypeType,
+ ScoreDomain,
+} from "@langfuse/shared";
+import {
+ filterAndValidateV3GetScoreList,
+ InternalServerError,
+ ScoreDataTypeEnum,
+} from "@langfuse/shared";
+
+export function polymorphicValue(score: {
+ dataType: ScoreDataTypeType;
+ value: number;
+ stringValue?: string | null;
+ longStringValue?: string | null;
+}): number | boolean | string {
+ switch (score.dataType) {
+ case ScoreDataTypeEnum.NUMERIC:
+ return score.value;
+ case ScoreDataTypeEnum.BOOLEAN:
+ return score.value === 1;
+ case ScoreDataTypeEnum.CATEGORICAL:
+ case ScoreDataTypeEnum.TEXT:
+ if (score.stringValue == null) {
+ throw new InternalServerError(
+ `Score with dataType ${score.dataType} is missing its stringValue`,
+ );
+ }
+ return score.stringValue;
+ case ScoreDataTypeEnum.CORRECTION:
+ if (score.longStringValue == null) {
+ throw new InternalServerError(
+ "Score with dataType CORRECTION is missing its longStringValue",
+ );
+ }
+ return score.longStringValue;
+ default: {
+ const _exhaustiveCheck: never = score.dataType;
+ throw new InternalServerError(
+ `Score has unknown dataType: ${_exhaustiveCheck as string}`,
+ );
+ }
+ }
+}
+
+function domainToV3(score: ScoreDomain): APIScoreV3 {
+ // ScoreDomain is a flat type so TypeScript cannot verify that dataType and
+ // value are a valid discriminated pair; polymorphicValue guarantees it at runtime.
+ return {
+ id: score.id,
+ projectId: score.projectId,
+ name: score.name,
+ dataType: score.dataType,
+ value: polymorphicValue({
+ dataType: score.dataType,
+ value: score.value,
+ stringValue: score.stringValue as string | null | undefined,
+ longStringValue: score.longStringValue as string | null | undefined,
+ }),
+ source: score.source,
+ timestamp: score.timestamp,
+ environment: score.environment,
+ createdAt: score.createdAt,
+ updatedAt: score.updatedAt,
+ } as APIScoreV3;
+}
+
+const v3ListQuery = `
+ SELECT
+ s.id as id,
+ s.project_id as project_id,
+ s.timestamp as timestamp,
+ s.environment as environment,
+ 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,
+ s.source as source,
+ s.comment as comment,
+ s.metadata as metadata,
+ s.data_type as data_type,
+ s.config_id as config_id,
+ s.queue_id as queue_id,
+ s.execution_trace_id as execution_trace_id,
+ s.trace_id as trace_id,
+ s.observation_id as observation_id,
+ s.session_id as session_id,
+ s.dataset_run_id as dataset_run_id
+ FROM scores s
+ WHERE s.project_id = {projectId: String}
+ ORDER BY s.timestamp DESC, s.id DESC, s.event_ts DESC
+ LIMIT 1 BY s.id, s.project_id
+ LIMIT {limit: Int32}
+`;
+
+export async function listScoresV3ForPublicApi(params: {
+ projectId: string;
+ limit: number;
+}): Promise<APIScoreV3[]> {
+ return measureAndReturn({
+ operationName: "listScoresV3ForPublicApi",
+ projectId: params.projectId,
+ input: {
+ params: { projectId: params.projectId, limit: params.limit },
+ tags: {
+ feature: "scoring",
+ type: "score",
+ projectId: params.projectId,
+ operation_name: "listScoresV3ForPublicApi",
+ },
+ },
+ fn: async (input) => {
+ const records = await queryClickhouse<ScoreRecordReadType>({
+ query: v3ListQuery,
+ params: input.params,
+ tags: input.tags,
+ preferredClickhouseService: "ReadOnly",
+ });
+ // Log+drop bad rows rather than 500ing the whole page — domainToV3 can
+ // throw (e.g. polymorphicValue's stringValue / longStringValue guards
+ // for malformed CATEGORICAL / TEXT / CORRECTION rows). Mirrors the
+ // row-level graceful-drop semantics of filterAndValidateV3GetScoreList.
+ const items: ReturnType<typeof domainToV3>[] = [];
+ for (const row of records) {
+ try {
+ items.push(domainToV3(convertClickhouseScoreToDomain(row)));
+ } catch (error) {
+ logger.error("v3 score row dropped from response", {
+ error,
+ scoreId: row.id,
+ projectId: params.projectId,
+ });
+ }
+ }
+ return filterAndValidateV3GetScoreList(items, (error) => {
+ logger.error("v3 score row dropped from response", {
+ issues: error.issues,
+ projectId: params.projectId,
+ });
+ });
+ },
+ });
+}
diff --git a/web/src/pages/api/public/v3/scores/index.ts b/web/src/pages/api/public/v3/scores/index.ts
new file mode 100644
index 0000000000..af94c45b53
--- /dev/null
+++ b/web/src/pages/api/public/v3/scores/index.ts
@@ -0,0 +1,36 @@
+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import {
+ GetScoresQueryV3,
+ GetScoresResponseV3,
+ LangfuseNotFoundError,
+} from "@langfuse/shared";
+import { listScoresV3ForPublicApi } from "@/src/features/public-api/server/scores-api-v3";
+import { env } from "@/src/env.mjs";
+
+export default withMiddlewares({
+ GET: createAuthedProjectAPIRoute({
+ name: "Get Scores V3",
+ querySchema: GetScoresQueryV3,
+ responseSchema: GetScoresResponseV3,
+ fn: async ({ query, auth }) => {
+ if (env.LANGFUSE_ENABLE_SCORES_V3_API !== "true") {
+ // Generic message to avoid disclosing the feature-flag existence to
+ // unauthenticated probes. Cloud has the flag on; self-hosted gets 404.
+ throw new LangfuseNotFoundError("Not Found");
+ }
+
+ const items = await listScoresV3ForPublicApi({
+ projectId: auth.scope.projectId,
+ limit: query.limit,
+ });
+
+ return {
+ data: items,
+ meta: {
+ limit: query.limit,
+ },
+ };
+ },
+ }),
+});