Skip to content

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

feat(scores): Add a score value filter to api (#1745)

Marc Klingend0cf2f56a0e1
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index f82c7343ed..a9181f3df1 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -209,6 +209,7 @@ types:
enum:
- API
- REVIEW
+ - EVAL
errors:
Error:
diff --git a/fern/apis/server/definition/score.yml b/fern/apis/server/definition/score.yml
index 1deeff05e0..781c2bf3ec 100644
--- a/fern/apis/server/definition/score.yml
+++ b/fern/apis/server/definition/score.yml
@@ -30,6 +30,15 @@ service:
fromTimestamp:
type: optional<datetime>
docs: Retrieve only scores newer than this timestamp.
+ source:
+ type: commons.ScoreSource
+ docs: Retrieve only scores from a specific source.
+ operator:
+ type: optional<string>
+ docs: Retrieve only scores with <operator> value.
+ value:
+ type: optional<double>
+ docs: Retrieve only scores with <operator> value.
response: Scores
get-by-id:
docs: Get a score
diff --git a/fern/fern.config.json b/fern/fern.config.json
index d7fc6f0791..123a7f31a2 100644
--- a/fern/fern.config.json
+++ b/fern/fern.config.json
@@ -1,4 +1,4 @@
{
"organization": "finto",
- "version": "0.19.30"
+ "version": "0.21.0"
}
\ No newline at end of file
diff --git a/generated/postman/collection.json b/generated/postman/collection.json
index 77cf5a517d..dca08b7a75 100644
--- a/generated/postman/collection.json
+++ b/generated/postman/collection.json
@@ -694,7 +694,7 @@
"request": {
"description": "Get a list of scores",
"url": {
- "raw": "{{baseUrl}}/api/public/scores?page=&limit=&userId=&name=&fromTimestamp=",
+ "raw": "{{baseUrl}}/api/public/scores?page=&limit=&userId=&name=&fromTimestamp=&source=&operator=&value=",
"host": [
"{{baseUrl}}"
],
@@ -728,6 +728,21 @@
"key": "fromTimestamp",
"value": "",
"description": "Retrieve only scores newer than this timestamp."
+ },
+ {
+ "key": "source",
+ "value": "",
+ "description": "Retrieve only scores from a specific source."
+ },
+ {
+ "key": "operator",
+ "value": "",
+ "description": "Retrieve only scores with <operator> value."
+ },
+ {
+ "key": "value",
+ "value": "",
+ "description": "Retrieve only scores with <operator> value."
}
],
"variable": []
diff --git a/web/generated/openapi-server/openapi.yml b/web/generated/openapi-server/openapi.yml
index eae54ecf6e..110d13734e 100644
--- a/web/generated/openapi-server/openapi.yml
+++ b/web/generated/openapi-server/openapi.yml
@@ -897,6 +897,27 @@ paths:
type: string
format: date-time
nullable: true
+ - name: source
+ in: query
+ description: Retrieve only scores from a specific source.
+ required: true
+ schema:
+ $ref: '#/components/schemas/ScoreSource'
+ - name: operator
+ in: query
+ description: Retrieve only scores with <operator> value.
+ required: false
+ schema:
+ type: string
+ nullable: true
+ - name: value
+ in: query
+ description: Retrieve only scores with <operator> value.
+ required: false
+ schema:
+ type: number
+ format: double
+ nullable: true
responses:
'200':
description: ''
@@ -1703,6 +1724,7 @@ components:
enum:
- API
- REVIEW
+ - EVAL
CreateDatasetItemRequest:
title: CreateDatasetItemRequest
type: object
diff --git a/web/src/__tests__/scores.servertest.ts b/web/src/__tests__/scores.servertest.ts
index 3a6e079401..33a3cdbe5f 100644
--- a/web/src/__tests__/scores.servertest.ts
+++ b/web/src/__tests__/scores.servertest.ts
@@ -5,8 +5,13 @@ import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
import { v4 as uuidv4 } from "uuid";
describe("/api/public/scores API Endpoint", () => {
- beforeEach(async () => await pruneDatabase());
- afterEach(async () => await pruneDatabase());
+ let should_prune_db = true;
+ beforeEach(async () => {
+ if (should_prune_db) await pruneDatabase();
+ });
+ afterEach(async () => {
+ if (should_prune_db) await pruneDatabase();
+ });
it("should create score for a trace", async () => {
await pruneDatabase();
@@ -316,4 +321,274 @@ describe("/api/public/scores API Endpoint", () => {
observationId: generationId,
});
});
+
+ describe("should Filter scores", () => {
+ const userId = "user-name";
+ const scoreName = "score-name";
+ const queryUserName = `userId=${userId}&name=${scoreName}`;
+ const traceId = uuidv4();
+ const generationId = uuidv4();
+ const scoreId_1 = uuidv4();
+ const scoreId_2 = uuidv4();
+ const scoreId_3 = uuidv4();
+ interface GetScoresAPIResponse {
+ data: [
+ {
+ id: string;
+ name: string;
+ value: number;
+ },
+ ];
+ meta: object;
+ }
+
+ beforeAll(async () => {
+ should_prune_db = false;
+ await pruneDatabase();
+
+ await makeAPICall("POST", "/api/public/traces", {
+ id: traceId,
+ userId: userId,
+ });
+ await makeAPICall("POST", "/api/public/generations", {
+ id: generationId,
+ });
+ await makeAPICall("POST", "/api/public/scores", {
+ id: scoreId_1,
+ observationId: generationId,
+ name: scoreName,
+ value: 10.5,
+ traceId: traceId,
+ comment: "comment",
+ });
+ await makeAPICall("POST", "/api/public/scores", {
+ id: scoreId_2,
+ observationId: generationId,
+ name: scoreName,
+ value: 50.5,
+ traceId: traceId,
+ comment: "comment",
+ });
+ await makeAPICall("POST", "/api/public/scores", {
+ id: scoreId_3,
+ observationId: generationId,
+ name: scoreName,
+ value: 100.8,
+ traceId: traceId,
+ comment: "comment",
+ });
+ });
+ afterAll(async () => {
+ await pruneDatabase();
+ });
+
+ it("get all scores", async () => {
+ const getAllScore = await makeAPICall<{
+ data: [
+ {
+ traceId: string;
+ observationId: string;
+ },
+ ];
+ meta: object;
+ }>("GET", `/api/public/scores?${queryUserName}`);
+ expect(getAllScore.status).toBe(200);
+ expect(getAllScore.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 3,
+ totalPages: 1,
+ });
+ for (const val of getAllScore.body.data) {
+ expect(val).toMatchObject({
+ traceId: traceId,
+ observationId: generationId,
+ });
+ }
+ });
+
+ it("test only operator", async () => {
+ const getScore = await makeAPICall<GetScoresAPIResponse>(
+ "GET",
+ `/api/public/scores?${queryUserName}&operator=<`,
+ );
+ expect(getScore.status).toBe(200);
+ expect(getScore.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 3,
+ totalPages: 1,
+ });
+ });
+
+ it("test only value", async () => {
+ const getScore = await makeAPICall<GetScoresAPIResponse>(
+ "GET",
+ `/api/public/scores?${queryUserName}&value=0.8`,
+ );
+ expect(getScore.status).toBe(200);
+ expect(getScore.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 3,
+ totalPages: 1,
+ });
+ });
+
+ it("test operator <", async () => {
+ const getScore = await makeAPICall<GetScoresAPIResponse>(
+ "GET",
+ `/api/public/scores?${queryUserName}&operator=<&value=50`,
+ );
+ expect(getScore.status).toBe(200);
+ expect(getScore.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 1,
+ totalPages: 1,
+ });
+ expect(getScore.body.data).toMatchObject([
+ {
+ id: scoreId_1,
+ name: scoreName,
+ value: 10.5,
+ },
+ ]);
+ });
+ it("test operator >", async () => {
+ const getScore = await makeAPICall<GetScoresAPIResponse>(
+ "GET",
+ `/api/public/scores?${queryUserName}&operator=>&value=100`,
+ );
+ expect(getScore.status).toBe(200);
+ expect(getScore.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 1,
+ totalPages: 1,
+ });
+ expect(getScore.body.data).toMatchObject([
+ {
+ id: scoreId_3,
+ name: scoreName,
+ value: 100.8,
+ },
+ ]);
+ });
+ it("test operator <=", async () => {
+ const getScore = await makeAPICall<GetScoresAPIResponse>(
+ "GET",
+ `/api/public/scores?${queryUserName}&operator=<=&value=50.5`,
+ );
+ expect(getScore.status).toBe(200);
+ expect(getScore.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 2,
+ totalPages: 1,
+ });
+ expect(getScore.body.data).toMatchObject([
+ {
+ id: scoreId_1,
+ name: scoreName,
+ value: 10.5,
+ },
+ {
+ id: scoreId_2,
+ name: scoreName,
+ value: 50.5,
+ },
+ ]);
+ });
+ it("test operator >=", async () => {
+ const getScore = await makeAPICall<GetScoresAPIResponse>(
+ "GET",
+ `/api/public/scores?${queryUserName}&operator=>=&value=50.5`,
+ );
+ expect(getScore.status).toBe(200);
+ expect(getScore.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 2,
+ totalPages: 1,
+ });
+ expect(getScore.body.data).toMatchObject([
+ {
+ id: scoreId_2,
+ name: scoreName,
+ value: 50.5,
+ },
+ {
+ id: scoreId_3,
+ name: scoreName,
+ value: 100.8,
+ },
+ ]);
+ });
+ it("test operator !=", async () => {
+ const getScore = await makeAPICall<GetScoresAPIResponse>(
+ "GET",
+ `/api/public/scores?${queryUserName}&operator=!=&value=50.5`,
+ );
+ expect(getScore.status).toBe(200);
+ expect(getScore.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 2,
+ totalPages: 1,
+ });
+ expect(getScore.body.data).toMatchObject([
+ {
+ id: scoreId_1,
+ name: scoreName,
+ value: 10.5,
+ },
+ {
+ id: scoreId_3,
+ name: scoreName,
+ value: 100.8,
+ },
+ ]);
+ });
+ it("test operator =", async () => {
+ const getScore = await makeAPICall<GetScoresAPIResponse>(
+ "GET",
+ `/api/public/scores?${queryUserName}&operator==&value=50.5`,
+ );
+ expect(getScore.status).toBe(200);
+ expect(getScore.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 1,
+ totalPages: 1,
+ });
+ expect(getScore.body.data).toMatchObject([
+ {
+ id: scoreId_2,
+ name: scoreName,
+ value: 50.5,
+ },
+ ]);
+ });
+ it("test invalid operator", async () => {
+ const getScore = await makeAPICall(
+ "GET",
+ `/api/public/scores?${queryUserName}&operator=op&value=50.5`,
+ );
+ expect(getScore.status).toBe(400);
+ expect(getScore.body).toMatchObject({
+ message: "Invalid request data",
+ });
+ });
+ it("test invalid value", async () => {
+ const getScore = await makeAPICall(
+ "GET",
+ `/api/public/scores?${queryUserName}&operator=<&value=myvalue`,
+ );
+ expect(getScore.status).toBe(400);
+ expect(getScore.body).toMatchObject({
+ message: "Invalid request data",
+ });
+ });
+ });
});
diff --git a/web/src/pages/api/public/scores.ts b/web/src/pages/api/public/scores.ts
index 44d3fb9b4e..14f632d0ea 100644
--- a/web/src/pages/api/public/scores.ts
+++ b/web/src/pages/api/public/scores.ts
@@ -1,4 +1,4 @@
-import { prisma } from "@langfuse/shared/src/db";
+import { ScoreSource, prisma } from "@langfuse/shared/src/db";
import { Prisma, type Score } from "@langfuse/shared/src/db";
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
@@ -18,11 +18,25 @@ import {
} from "@/src/pages/api/public/ingestion";
import { isPrismaException } from "@/src/utils/exceptions";
+const operators = ["<", ">", "<=", ">=", "!=", "="] as const;
+
+const prismaOperators: Record<(typeof operators)[number], string> = {
+ "<": "lt",
+ ">": "gt",
+ "<=": "lte",
+ ">=": "gte",
+ "!=": "not",
+ "=": "equals",
+};
+
const ScoresGetSchema = z.object({
...paginationZod,
userId: z.string().nullish(),
name: z.string().nullish(),
fromTimestamp: stringDate,
+ source: z.nativeEnum(ScoreSource).nullish(),
+ value: z.coerce.number().nullish(),
+ operator: z.enum(operators).nullish(),
});
export default async function handler(
@@ -105,6 +119,13 @@ export default async function handler(
const fromTimestampCondition = obj.fromTimestamp
? Prisma.sql`AND t."timestamp" >= ${obj.fromTimestamp}::timestamp with time zone at time zone 'UTC'`
: Prisma.empty;
+ const sourceCondition = obj.source
+ ? Prisma.sql`AND s."source" = ${obj.source}`
+ : Prisma.empty;
+ const valueCondition =
+ obj.operator && obj.value !== null && obj.value !== undefined
+ ? Prisma.sql`AND s."value" ${Prisma.raw(`${obj.operator}`)} ${obj.value}`
+ : Prisma.empty;
const scores = await prisma.$queryRaw<
Array<Score & { trace: { userId: string } }>
@@ -114,6 +135,7 @@ export default async function handler(
s.timestamp,
s.name,
s.value,
+ s.source,
s.comment,
s.trace_id as "traceId",
s.observation_id as "observationId",
@@ -123,16 +145,25 @@ export default async function handler(
WHERE t.project_id = ${authCheck.scope.projectId}
${userCondition}
${nameCondition}
+ ${sourceCondition}
${fromTimestampCondition}
+ ${valueCondition}
ORDER BY t."timestamp" DESC
LIMIT ${obj.limit} OFFSET ${skipValue}
`);
const totalItems = await prisma.score.count({
where: {
name: obj.name ? obj.name : undefined,
+ source: obj.source ? obj.source : undefined,
timestamp: obj.fromTimestamp
? { gte: new Date(obj.fromTimestamp) }
: undefined,
+ value:
+ obj.operator && obj.value
+ ? {
+ [prismaOperators[obj.operator]]: obj.value,
+ }
+ : undefined,
trace: {
projectId: authCheck.scope.projectId,
userId: obj.userId ? obj.userId : undefined,