Skip to content

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

refactor(scores-api): simplify types, ensure return types of API are consistent in documentation and return (#2565)

marliessophie0223c7eff118
diff --git a/fern/apis/client/definition/score.yml b/fern/apis/client/definition/score.yml
index b273db3457..e269551770 100644
--- a/fern/apis/client/definition/score.yml
+++ b/fern/apis/client/definition/score.yml
@@ -9,7 +9,6 @@ service:
method: POST
path: /scores
request: CreateScoreRequest
- response: Score
types:
CreateScoreRequest:
@@ -65,57 +64,45 @@ types:
dataType: "BOOLEAN"
configId: "1234-5678-90ab-cdef"
traceId: "cdef-1234-5678-90ab"
- NumericScore:
+ BaseScore:
properties:
id: string
traceId: string
name: string
- value:
- type: double
- docs: The numeric value of the score
source: ScoreSource
observationId: optional<string>
timestamp: datetime
+ createdAt: datetime
+ updatedAt: datetime
+ authorUserId: optional<string>
comment: optional<string>
configId:
type: optional<string>
docs: Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range
+ NumericScore:
+ extends: BaseScore
+ properties:
+ value:
+ type: double
+ docs: The numeric value of the score
BooleanScore:
+ extends: BaseScore
properties:
- id: string
- traceId: string
- name: string
value:
type: double
docs: The numeric value of the score. Equals 1 for "True" and 0 for "False"
stringValue:
type: string
docs: The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"
- source: ScoreSource
- observationId: optional<string>
- timestamp: datetime
- comment: optional<string>
- configId:
- type: optional<string>
- docs: Reference a score config on a score. When set, config and score name must be equal
CategoricalScore:
+ extends: BaseScore
properties:
- id: string
- traceId: string
- name: string
value:
type: optional<double>
docs: Only defined if a config is linked. Represents the numeric category mapping of the stringValue
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
- source: ScoreSource
- observationId: optional<string>
- timestamp: datetime
- comment: optional<string>
- configId:
- type: optional<string>
- docs: Reference a score config on a score. When set, config and score name must be equal and stringValue must map to a config category
Score:
discriminant: "dataType"
union:
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index 9ea27044b9..d281590167 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -137,57 +137,45 @@ types:
properties:
value: double
label: string
- NumericScore:
+ BaseScore:
properties:
id: string
traceId: string
name: string
- value:
- type: double
- docs: The numeric value of the score
source: ScoreSource
observationId: optional<string>
timestamp: datetime
+ createdAt: datetime
+ updatedAt: datetime
+ authorUserId: optional<string>
comment: optional<string>
configId:
type: optional<string>
docs: Reference a score config on a score. When set, config and score name must be equal and value must comply to optionally defined numerical range
+ NumericScore:
+ extends: BaseScore
+ properties:
+ value:
+ type: double
+ docs: The numeric value of the score
BooleanScore:
+ extends: BaseScore
properties:
- id: string
- traceId: string
- name: string
value:
type: double
docs: The numeric value of the score. Equals 1 for "True" and 0 for "False"
stringValue:
type: string
docs: The string representation of the score value. Is inferred from the numeric value and equals "True" or "False"
- source: ScoreSource
- observationId: optional<string>
- timestamp: datetime
- comment: optional<string>
- configId:
- type: optional<string>
- docs: Reference a score config on a score. When set, config and score name must be equal
CategoricalScore:
+ extends: BaseScore
properties:
- id: string
- traceId: string
- name: string
value:
type: optional<double>
docs: Only defined if a config is linked. Represents the numeric category mapping of the stringValue
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
- source: ScoreSource
- observationId: optional<string>
- timestamp: datetime
- comment: optional<string>
- configId:
- type: optional<string>
- docs: Reference a score config on a score. When set, config and score name must be equal and stringValue must map to a config category
Score:
discriminant: "dataType"
union:
diff --git a/web/public/generated/api-client/openapi.yml b/web/public/generated/api-client/openapi.yml
index 30604ff66d..117bed2594 100644
--- a/web/public/generated/api-client/openapi.yml
+++ b/web/public/generated/api-client/openapi.yml
@@ -11,12 +11,8 @@ paths:
- Score
parameters: []
responses:
- '200':
+ '204':
description: ''
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Score'
'400':
description: ''
content:
@@ -90,8 +86,8 @@ components:
- traceId
- name
- value
- NumericScore:
- title: NumericScore
+ BaseScore:
+ title: BaseScore
type: object
properties:
id:
@@ -100,10 +96,6 @@ components:
type: string
name:
type: string
- value:
- type: number
- format: double
- description: The numeric value of the score
source:
$ref: '#/components/schemas/ScoreSource'
observationId:
@@ -111,6 +103,14 @@ components:
timestamp:
type: string
format: date-time
+ createdAt:
+ type: string
+ format: date-time
+ updatedAt:
+ type: string
+ format: date-time
+ authorUserId:
+ type: string
comment:
type: string
configId:
@@ -123,19 +123,26 @@ components:
- id
- traceId
- name
- - value
- source
- timestamp
+ - createdAt
+ - updatedAt
+ NumericScore:
+ title: NumericScore
+ type: object
+ properties:
+ value:
+ type: number
+ format: double
+ description: The numeric value of the score
+ required:
+ - value
+ allOf:
+ - $ref: '#/components/schemas/BaseScore'
BooleanScore:
title: BooleanScore
type: object
properties:
- id:
- type: string
- traceId:
- type: string
- name:
- type: string
value:
type: number
format: double
@@ -147,38 +154,15 @@ components:
description: >-
The string representation of the score value. Is inferred from the
numeric value and equals "True" or "False"
- source:
- $ref: '#/components/schemas/ScoreSource'
- observationId:
- type: string
- timestamp:
- type: string
- format: date-time
- comment:
- type: string
- configId:
- type: string
- description: >-
- Reference a score config on a score. When set, config and score name
- must be equal
required:
- - id
- - traceId
- - name
- value
- stringValue
- - source
- - timestamp
+ allOf:
+ - $ref: '#/components/schemas/BaseScore'
CategoricalScore:
title: CategoricalScore
type: object
properties:
- id:
- type: string
- traceId:
- type: string
- name:
- type: string
value:
type: number
format: double
@@ -190,27 +174,10 @@ components:
description: >-
The string representation of the score value. If no config is
linked, can be any string. Otherwise, must map to a config category
- source:
- $ref: '#/components/schemas/ScoreSource'
- observationId:
- type: string
- timestamp:
- type: string
- format: date-time
- comment:
- type: string
- configId:
- type: string
- description: >-
- Reference a score config on a score. When set, config and score name
- must be equal and stringValue must map to a config category
required:
- - id
- - traceId
- - name
- stringValue
- - source
- - timestamp
+ allOf:
+ - $ref: '#/components/schemas/BaseScore'
Score:
title: Score
oneOf:
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index b6868df5bb..17b81648dc 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -2176,8 +2176,8 @@ components:
required:
- value
- label
- NumericScore:
- title: NumericScore
+ BaseScore:
+ title: BaseScore
type: object
properties:
id:
@@ -2186,10 +2186,6 @@ components:
type: string
name:
type: string
- value:
- type: number
- format: double
- description: The numeric value of the score
source:
$ref: '#/components/schemas/ScoreSource'
observationId:
@@ -2198,6 +2194,15 @@ components:
timestamp:
type: string
format: date-time
+ createdAt:
+ type: string
+ format: date-time
+ updatedAt:
+ type: string
+ format: date-time
+ authorUserId:
+ type: string
+ nullable: true
comment:
type: string
nullable: true
@@ -2212,19 +2217,26 @@ components:
- id
- traceId
- name
- - value
- source
- timestamp
+ - createdAt
+ - updatedAt
+ NumericScore:
+ title: NumericScore
+ type: object
+ properties:
+ value:
+ type: number
+ format: double
+ description: The numeric value of the score
+ required:
+ - value
+ allOf:
+ - $ref: '#/components/schemas/BaseScore'
BooleanScore:
title: BooleanScore
type: object
properties:
- id:
- type: string
- traceId:
- type: string
- name:
- type: string
value:
type: number
format: double
@@ -2236,41 +2248,15 @@ components:
description: >-
The string representation of the score value. Is inferred from the
numeric value and equals "True" or "False"
- source:
- $ref: '#/components/schemas/ScoreSource'
- observationId:
- type: string
- nullable: true
- timestamp:
- type: string
- format: date-time
- comment:
- type: string
- nullable: true
- configId:
- type: string
- nullable: true
- description: >-
- Reference a score config on a score. When set, config and score name
- must be equal
required:
- - id
- - traceId
- - name
- value
- stringValue
- - source
- - timestamp
+ allOf:
+ - $ref: '#/components/schemas/BaseScore'
CategoricalScore:
title: CategoricalScore
type: object
properties:
- id:
- type: string
- traceId:
- type: string
- name:
- type: string
value:
type: number
format: double
@@ -2283,30 +2269,10 @@ components:
description: >-
The string representation of the score value. If no config is
linked, can be any string. Otherwise, must map to a config category
- source:
- $ref: '#/components/schemas/ScoreSource'
- observationId:
- type: string
- nullable: true
- timestamp:
- type: string
- format: date-time
- comment:
- type: string
- nullable: true
- configId:
- type: string
- nullable: true
- description: >-
- Reference a score config on a score. When set, config and score name
- must be equal and stringValue must map to a config category
required:
- - id
- - traceId
- - name
- stringValue
- - source
- - timestamp
+ allOf:
+ - $ref: '#/components/schemas/BaseScore'
Score:
title: Score
oneOf:
diff --git a/web/src/__tests__/scores.servertest.ts b/web/src/__tests__/scores.servertest.ts
index 5951061228..fb095c4a39 100644
--- a/web/src/__tests__/scores.servertest.ts
+++ b/web/src/__tests__/scores.servertest.ts
@@ -105,6 +105,39 @@ describe("/api/public/scores API Endpoint", () => {
expect(fetchedScore.body?.observationId).toBeNull();
});
+ it("should GET score with minimal score data and minimal trace data", async () => {
+ const minimalTraceId = uuidv4();
+ await makeAPICall("POST", "/api/public/traces", {
+ id: minimalTraceId,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ });
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ id: minimalTraceId,
+ },
+ });
+
+ expect(dbTrace.length).toBeGreaterThan(0);
+ expect(dbTrace[0]?.id).toBe(minimalTraceId);
+
+ const minimalScoreId = uuidv4();
+
+ await makeAPICall("POST", "/api/public/scores", {
+ id: minimalScoreId,
+ name: "score-name",
+ value: 100,
+ traceId: minimalTraceId,
+ });
+
+ const fetchedScore = await makeZodVerifiedAPICall(
+ GetScoreResponse,
+ "GET",
+ `/api/public/scores/${minimalScoreId}`,
+ );
+
+ expect(fetchedScore.status).toBe(200);
+ });
+
it("should create score for a generation", async () => {
await pruneDatabase();
@@ -1124,6 +1157,45 @@ describe("/api/public/scores API Endpoint", () => {
},
]);
});
+ it("should GET ALL scores with minimal score data and minimal trace data", async () => {
+ const minimalTraceId = uuidv4();
+ await makeAPICall("POST", "/api/public/traces", {
+ id: minimalTraceId,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ });
+ const dbTrace = await prisma.trace.findMany({
+ where: {
+ id: minimalTraceId,
+ },
+ });
+
+ expect(dbTrace.length).toBeGreaterThan(0);
+ expect(dbTrace[0]?.id).toBe(minimalTraceId);
+
+ const createScore = await makeAPICall("POST", "/api/public/scores", {
+ name: "score-name",
+ value: 100,
+ traceId: minimalTraceId,
+ });
+
+ expect(createScore.status).toBe(200);
+
+ const fetchedScores = await makeZodVerifiedAPICall(
+ GetScoresResponse,
+ "GET",
+ `/api/public/scores`,
+ );
+
+ expect(fetchedScores.status).toBe(200);
+ expect(fetchedScores.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 4,
+ totalPages: 1,
+ });
+ expect(fetchedScores.body.data.length).toBe(4);
+ });
+
it("test invalid operator", async () => {
try {
await makeZodVerifiedAPICall(
diff --git a/web/src/features/public-api/types/score-configs.ts b/web/src/features/public-api/types/score-configs.ts
index ac14b7b06b..e2daece4c2 100644
--- a/web/src/features/public-api/types/score-configs.ts
+++ b/web/src/features/public-api/types/score-configs.ts
@@ -8,6 +8,12 @@ import {
import { z } from "zod";
import * as Sentry from "@sentry/node";
+/**
+ * Types to use across codebase
+ */
+export type ConfigCategory = z.infer<typeof Category>;
+export type ValidatedScoreConfig = z.infer<typeof ValidatedScoreConfigSchema>;
+
const validateCategories = (
categories: ConfigCategory[],
ctx: z.RefinementCtx,
@@ -44,8 +50,6 @@ export const Category = z.object({
value: z.number(),
});
-export type ConfigCategory = z.infer<typeof Category>;
-
const Categories = z.array(Category);
const NumericScoreConfig = z.object({
@@ -137,8 +141,12 @@ const ValidatedScoreConfigSchema = z
}
});
-export type ValidatedScoreConfig = z.infer<typeof ValidatedScoreConfigSchema>;
-
+/**
+ * Use this function when pulling a list of score configs from the database before using in the application to ensure type safety.
+ * All score configs are expected to pass the validation. If a score fails validation, it will be logged to Sentry.
+ * @param scoreConfigs
+ * @returns list of validated score configs
+ */
export const filterAndValidateDbScoreConfigList = (
scoreConfigs: ScoreConfigDbType[],
): ValidatedScoreConfig[] =>
@@ -152,10 +160,26 @@ export const filterAndValidateDbScoreConfigList = (
return acc;
}, [] as ValidatedScoreConfig[]);
+/**
+ * Use this function when pulling a single score config from the database before using in the application to ensure type safety.
+ * The score is expected to pass the validation. If a score fails validation, an error will be thrown.
+ * @param scoreConfig
+ * @returns validated score config
+ * @throws error if score fails validation
+ */
export const validateDbScoreConfig = (
scoreConfig: ScoreConfigDbType,
): ValidatedScoreConfig => ValidatedScoreConfigSchema.parse(scoreConfig);
+/**
+ * Use this function when pulling a single score config from the database before using in the application to ensure type safety.
+ * This function will NOT throw an error by default. The score is expected to pass the validation.
+ * @param scoreConfig
+ * @returns score config validation object:
+ * - success: true if the score config passes validation
+ * - data: the validated score config if success is true
+ * - error: the error object if success is false
+ */
export const validateDbScoreConfigSafe = (scoreConfig: ScoreConfigDbType) =>
ValidatedScoreConfigSchema.safeParse(scoreConfig);
diff --git a/web/src/features/public-api/types/scores.ts b/web/src/features/public-api/types/scores.ts
index e9eca27533..9325a4ee2e 100644
--- a/web/src/features/public-api/types/scores.ts
+++ b/web/src/features/public-api/types/scores.ts
@@ -9,6 +9,11 @@ import { z } from "zod";
import { isPresent } from "@/src/utils/typeChecks";
import { Category as ConfigCategory } from "./score-configs";
+/**
+ * Types to use across codebase
+ */
+export type ValidatedScore = z.infer<typeof ValidatedScoreSchema>;
+
/**
* Objects
*/
@@ -59,36 +64,12 @@ const BaseScoreBody = z.object({
comment: z.string().nullish(),
});
-const GetScoresDataBase = z.object({
- id: z.string(),
- timestamp: z.coerce.date(),
- name: z.string(),
- source: z.enum(ScoreSource),
- comment: z.string().nullish(),
- traceId: z.string(),
- observationId: z.string().nullish(),
- trace: z.object({
- userId: z.string().nullish(),
- }),
- configId: z.string().nullish(),
-});
-
-export const GetScoresData = z.discriminatedUnion("dataType", [
- GetScoresDataBase.merge(NumericData),
- GetScoresDataBase.merge(CategoricalData),
- GetScoresDataBase.merge(BooleanData),
-]);
-
const ValidatedScoreSchema = z.discriminatedUnion("dataType", [
ScoreBase.merge(NumericData),
ScoreBase.merge(CategoricalData),
ScoreBase.merge(BooleanData),
]);
-export type ValidatedGetScoresData = z.infer<typeof GetScoresData>;
-
-export type ValidatedScore = z.infer<typeof ValidatedScoreSchema>;
-
/**
* Validation objects
*/
@@ -167,6 +148,12 @@ export const ScorePropsAgainstConfig = z.union([
* Transformations
*/
+/**
+ * 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 Sentry.
+ * @param scores
+ * @returns list of validated scores
+ */
export const filterAndValidateDbScoreList = (
scores: Score[],
): ValidatedScore[] =>
@@ -175,11 +162,19 @@ export const filterAndValidateDbScoreList = (
if (result.success) {
acc.push(result.data);
} else {
+ console.error("Score parsing error: ", result.error);
Sentry.captureException(result.error);
}
return acc;
}, [] as ValidatedScore[]);
+/**
+ * Use this function when pulling a single score from the database before using in the application to ensure type safety.
+ * The score is expected to pass the validation. If a score fails validation, an error will be thrown.
+ * @param score
+ * @returns validated score
+ * @throws error if score fails validation
+ */
export const validateDbScore = (score: Score): ValidatedScore =>
ValidatedScoreSchema.parse(score);
@@ -271,11 +266,37 @@ export const GetScoresQuery = z.object({
.nullish(),
});
+// LegacyGetScoreResponseDataV1 is only used for response of GET /scores list endpoint
+const LegacyGetScoreResponseDataV1 = z.intersection(
+ ValidatedScoreSchema,
+ z.object({
+ trace: z.object({
+ userId: z.string().nullish(),
+ }),
+ }),
+);
export const GetScoresResponse = z.object({
- data: z.array(GetScoresData),
+ data: z.array(LegacyGetScoreResponseDataV1),
meta: paginationMetaResponseZod,
});
+export const legacyFilterAndValidateV1GetScoreList = (
+ scores: unknown[],
+): z.infer<typeof LegacyGetScoreResponseDataV1>[] =>
+ scores.reduce(
+ (acc: z.infer<typeof LegacyGetScoreResponseDataV1>[], ts) => {
+ const result = LegacyGetScoreResponseDataV1.safeParse(ts);
+ if (result.success) {
+ acc.push(result.data);
+ } else {
+ console.error("Score parsing error: ", result.error);
+ Sentry.captureException(result.error);
+ }
+ return acc;
+ },
+ [] as z.infer<typeof LegacyGetScoreResponseDataV1>[],
+ );
+
// GET /scores/{scoreId}
export const GetScoreQuery = z.object({
scoreId: z.string(),
diff --git a/web/src/pages/api/public/events.ts b/web/src/pages/api/public/events.ts
index e62282c536..92794cb1ff 100644
--- a/web/src/pages/api/public/events.ts
+++ b/web/src/pages/api/public/events.ts
@@ -9,7 +9,7 @@ import {
} from "@langfuse/shared";
import {
handleBatch,
- handleBatchResultLegacy,
+ handleSingleIngestionObject,
} from "@/src/pages/api/public/ingestion";
import { z } from "zod";
import { isPrismaException } from "@/src/utils/exceptions";
@@ -64,7 +64,7 @@ export default async function handler(
req,
authCheck,
);
- handleBatchResultLegacy(result.errors, result.results, res);
+ handleSingleIngestionObject(result.errors, result.results, res);
} catch (error: unknown) {
console.error(error);
if (error instanceof z.ZodError) {
diff --git a/web/src/pages/api/public/generations.ts b/web/src/pages/api/public/generations.ts
index 82fc82fdbc..3c379aa94d 100644
--- a/web/src/pages/api/public/generations.ts
+++ b/web/src/pages/api/public/generations.ts
@@ -11,7 +11,7 @@ import {
} from "@langfuse/shared";
import {
handleBatch,
- handleBatchResultLegacy,
+ handleSingleIngestionObject,
} from "@/src/pages/api/public/ingestion";
import { z } from "zod";
import { isPrismaException } from "@/src/utils/exceptions";
@@ -22,6 +22,7 @@ export default async function handler(
) {
await runMiddleware(req, res, cors);
+ // POST endpoint defined for backwards compatibility only. Observations should be created via the ingestion endpoint
if (req.method === "POST") {
try {
// CHECK AUTH
@@ -67,7 +68,7 @@ export default async function handler(
authCheck,
);
- handleBatchResultLegacy(result.errors, result.results, res);
+ handleSingleIngestionObject(result.errors, result.results, res);
} catch (error: unknown) {
console.error(error);
if (error instanceof z.ZodError) {
@@ -132,7 +133,7 @@ export default async function handler(
authCheck,
);
- handleBatchResultLegacy(result.errors, result.results, res);
+ handleSingleIngestionObject(result.errors, result.results, res);
} catch (error: unknown) {
console.error(error);
if (error instanceof z.ZodError) {
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index 4e1ad05bdd..b46c22212f 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -401,7 +401,7 @@ export const handleBatchResult = (
return res.status(207).send({ errors: returnedErrors, successes });
};
-export const handleBatchResultLegacy = (
+export const handleSingleIngestionObject = (
errors: Array<{ id: string; error: unknown }>,
results: Array<{ id: string; result: unknown }>,
res: NextApiResponse,
diff --git a/web/src/pages/api/public/scores.ts b/web/src/pages/api/public/scores.ts
index 1181b2c337..1c3d96a843 100644
--- a/web/src/pages/api/public/scores.ts
+++ b/web/src/pages/api/public/scores.ts
@@ -1,21 +1,19 @@
import { prisma } from "@langfuse/shared/src/db";
import { Prisma } from "@langfuse/shared/src/db";
import { eventTypes, ingestionBatchEvent } from "@langfuse/shared";
-import * as Sentry from "@sentry/node";
import { v4 } from "uuid";
import {
handleBatch,
- handleBatchResultLegacy,
+ handleSingleIngestionObject,
} from "@/src/pages/api/public/ingestion";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
import {
- GetScoresData,
GetScoresQuery,
GetScoresResponse,
PostScoresBody,
PostScoresResponse,
- type ValidatedGetScoresData,
+ legacyFilterAndValidateV1GetScoreList,
} from "@/src/features/public-api/types/scores";
export default withMiddlewares({
@@ -36,7 +34,7 @@ export default withMiddlewares({
req,
auth,
);
- handleBatchResultLegacy(result.errors, result.results, res);
+ handleSingleIngestionObject(result.errors, result.results, res);
},
}),
GET: createAuthedAPIRoute({
@@ -92,6 +90,10 @@ export default withMiddlewares({
s.name,
s.value,
s.string_value as "stringValue",
+ s.author_user_id as "authorUserId",
+ s.project_id as "projectId",
+ s.created_at as "createdAt",
+ s.updated_at as "updatedAt",
s.source,
s.comment,
s.data_type as "dataType",
@@ -131,19 +133,7 @@ export default withMiddlewares({
`,
);
- const validatedScores = scores.reduce(
- (acc: ValidatedGetScoresData[], score) => {
- const result = GetScoresData.safeParse(score);
- if (result.success) {
- acc.push(result.data);
- } else {
- console.error("Score parsing error: ", result.error);
- Sentry.captureException(result.error);
- }
- return acc;
- },
- [] as ValidatedGetScoresData[],
- );
+ const validatedScores = legacyFilterAndValidateV1GetScoreList(scores);
const totalItems =
totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;
diff --git a/web/src/pages/api/public/spans.ts b/web/src/pages/api/public/spans.ts
index 95c2417c01..3173fa04b3 100644
--- a/web/src/pages/api/public/spans.ts
+++ b/web/src/pages/api/public/spans.ts
@@ -11,7 +11,7 @@ import {
} from "@langfuse/shared";
import {
handleBatch,
- handleBatchResultLegacy,
+ handleSingleIngestionObject,
} from "@/src/pages/api/public/ingestion";
import { z } from "zod";
import { isPrismaException } from "@/src/utils/exceptions";
@@ -32,6 +32,7 @@ export default async function handler(
});
// END CHECK AUTH
+ // POST endpoint defined for backwards compatibility only. Spans should be created via the ingestion endpoint
if (req.method === "POST") {
try {
console.log(
@@ -63,7 +64,7 @@ export default async function handler(
req,
authCheck,
);
- handleBatchResultLegacy(result.errors, result.results, res);
+ handleSingleIngestionObject(result.errors, result.results, res);
} catch (error: unknown) {
if (isPrismaException(error)) {
return res.status(500).json({
@@ -117,7 +118,7 @@ export default async function handler(
authCheck,
);
- handleBatchResultLegacy(result.errors, result.results, res);
+ handleSingleIngestionObject(result.errors, result.results, res);
} catch (error: unknown) {
console.error(error);
diff --git a/web/src/pages/api/public/traces.ts b/web/src/pages/api/public/traces.ts
index ee453c4d57..ea2a0dbb64 100644
--- a/web/src/pages/api/public/traces.ts
+++ b/web/src/pages/api/public/traces.ts
@@ -7,7 +7,7 @@ import { Prisma, type Trace } from "@langfuse/shared/src/db";
import { paginationZod } from "@langfuse/shared";
import {
handleBatch,
- handleBatchResultLegacy,
+ handleSingleIngestionObject,
} from "@/src/pages/api/public/ingestion";
import { TraceBody, eventTypes, stringDate } from "@langfuse/shared";
import { v4 } from "uuid";
@@ -50,6 +50,7 @@ export default async function handler(
// END CHECK AUTH
try {
+ // POST endpoint defined for backwards compatibility only. Traces should be created via the ingestion endpoint
if (req.method === "POST") {
console.log(
"Trying to create trace, project ",
@@ -76,7 +77,7 @@ export default async function handler(
};
const result = await handleBatch([event], {}, req, authCheck);
- handleBatchResultLegacy(result.errors, result.results, res);
+ handleSingleIngestionObject(result.errors, result.results, res);
} else if (req.method === "GET") {
if (authCheck.scope.accessLevel !== "all") {
return res.status(401).json({
diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].ts
index a4e17422c8..2eeedaa1cb 100644
--- a/web/src/pages/api/public/traces/[traceId].ts
+++ b/web/src/pages/api/public/traces/[traceId].ts
@@ -5,6 +5,7 @@ import { prisma } from "@langfuse/shared/src/db";
import { isPrismaException } from "@/src/utils/exceptions";
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
+import { filterAndValidateDbScoreList } from "@/src/features/public-api/types/scores";
const GetTraceSchema = z.object({
traceId: z.string(),
@@ -74,7 +75,7 @@ export default async function handler(
return res.status(200).json({
...trace,
- scores,
+ scores: filterAndValidateDbScoreList(scores),
htmlPath: `/project/${authCheck.scope.projectId}/traces/${traceId}`,
totalCost: outObservations.reduce(
(acc, obs) => acc + (obs.calculatedTotalCost ?? 0),