Skip to content

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

feat: fetch scores by id via API from clickhouse (#4291)

Max Deichmann2068ba7314ef
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index 2383faa7f2..61654a712c 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -90,14 +90,14 @@ export const searchExistingAnnotationScore = async (
export const getScoreById = async (
projectId: string,
scoreId: string,
- source: ScoreSource,
+ source?: ScoreSource,
) => {
const query = `
SELECT *
FROM scores s
WHERE s.project_id = {projectId: String}
AND s.id = {scoreId: String}
- AND s.source = {source: String}
+ ${source ? `AND s.source = {source: String}` : ""}
ORDER BY s.event_ts DESC
LIMIT 1 BY s.id, s.project_id
LIMIT 1
@@ -108,7 +108,7 @@ export const getScoreById = async (
params: {
projectId,
scoreId,
- source,
+ ...(source !== undefined ? { source } : {}),
},
});
return rows.map(convertToScore).shift();
diff --git a/web/src/__tests__/async/scores-api.servertest.ts b/web/src/__tests__/async/scores-api.servertest.ts
new file mode 100644
index 0000000000..da1a993681
--- /dev/null
+++ b/web/src/__tests__/async/scores-api.servertest.ts
@@ -0,0 +1,51 @@
+import { createScores } from "@/src/__tests__/server/repositories/clickhouse-helpers";
+import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";
+import { GetScoreResponse } from "@langfuse/shared";
+import { v4 } from "uuid";
+
+const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+describe("/api/public/scores API Endpoint", () => {
+ describe("GET /api/public/scores/:scoreId", () => {
+ it("should GET a score", async () => {
+ const scoreId = v4();
+ const traceId = v4();
+ const score = {
+ id: scoreId,
+ project_id: projectId,
+ trace_id: traceId,
+ name: "Test Score",
+ timestamp: Date.now(),
+ observation_id: v4(),
+ value: 100.5,
+ source: "API",
+ comment: "comment",
+ data_type: "NUMERIC" as const,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ is_deleted: 0,
+ };
+
+ await createScores([score]);
+
+ const getScore = await makeZodVerifiedAPICall(
+ GetScoreResponse,
+ "GET",
+ `/api/public/scores/${scoreId}`,
+ );
+
+ expect(getScore.status).toBe(200);
+ expect(getScore.body).toMatchObject({
+ id: scoreId,
+ name: "Test Score",
+ value: 100.5,
+ comment: "comment",
+ source: "API",
+ traceId,
+ observationId: score.observation_id,
+ dataType: "NUMERIC",
+ });
+ });
+ });
+});
diff --git a/web/src/__tests__/async/some.servertest.ts b/web/src/__tests__/async/some.servertest.ts
deleted file mode 100644
index dcae564420..0000000000
--- a/web/src/__tests__/async/some.servertest.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-describe("Sample Test Suite", () => {
- it("should return true for a simple truthy test", () => {
- expect(true).toBe(true);
- });
-
- it("should add two numbers correctly", () => {
- const sum = (a: number, b: number) => a + b;
- expect(sum(1, 2)).toBe(3);
- });
-});
diff --git a/web/src/__tests__/scores.servertest.ts b/web/src/__tests__/scores.servertest.ts
index 80be1a8f73..ea541060d1 100644
--- a/web/src/__tests__/scores.servertest.ts
+++ b/web/src/__tests__/scores.servertest.ts
@@ -36,7 +36,7 @@ describe("/api/public/scores API Endpoint", () => {
version: "2.0.0",
},
);
- });
+ }, 10000);
afterEach(async () => {
if (should_prune_db) await pruneDatabase();
});
@@ -827,58 +827,6 @@ describe("/api/public/scores API Endpoint", () => {
expect(deletedScore).toBeNull();
});
- it("should GET a score", async () => {
- await pruneDatabase();
-
- const traceId = uuidv4();
-
- await makeZodVerifiedAPICall(
- PostTracesV1Response,
- "POST",
- "/api/public/traces",
- {
- id: traceId,
- },
- );
- const generationId = uuidv4();
- await makeZodVerifiedAPICall(
- PostTracesV1Response,
- "POST",
- "/api/public/generations",
- {
- id: generationId,
- },
- );
-
- const scoreId = uuidv4();
- await makeAPICall("POST", "/api/public/scores", {
- id: scoreId,
- observationId: generationId,
- name: "score-name",
- value: 100.5,
- traceId: traceId,
- comment: "comment",
- });
-
- const getScore = await makeZodVerifiedAPICall(
- GetScoreResponse,
- "GET",
- `/api/public/scores/${scoreId}`,
- );
-
- expect(getScore.status).toBe(200);
- expect(getScore.body).toMatchObject({
- id: scoreId,
- name: "score-name",
- value: 100.5,
- comment: "comment",
- source: "API",
- traceId,
- observationId: generationId,
- dataType: "NUMERIC",
- });
- });
-
describe("should Filter scores", () => {
let configId = "";
const userId = "user-name";
diff --git a/web/src/__tests__/server/repositories/clickhouse-helpers.ts b/web/src/__tests__/server/repositories/clickhouse-helpers.ts
index 1732f10147..13ab5c20cf 100644
--- a/web/src/__tests__/server/repositories/clickhouse-helpers.ts
+++ b/web/src/__tests__/server/repositories/clickhouse-helpers.ts
@@ -1,5 +1,6 @@
import {
clickhouseClient,
+ type ScoreRecordInsertType,
type ObservationRecordInsertType,
type TraceRecordInsertType,
} from "@langfuse/shared/src/server";
@@ -31,3 +32,11 @@ export const createObservations = async (
values: observations,
});
};
+
+export const createScores = async (scores: ScoreRecordInsertType[]) => {
+ return await clickhouseClient.insert({
+ table: "scores",
+ format: "JSONEachRow",
+ values: scores,
+ });
+};
diff --git a/web/src/__tests__/server/repositories/score-repository.servertest.ts b/web/src/__tests__/server/repositories/score-repository.servertest.ts
new file mode 100644
index 0000000000..bd3ce88b1e
--- /dev/null
+++ b/web/src/__tests__/server/repositories/score-repository.servertest.ts
@@ -0,0 +1,51 @@
+import { createScores } from "@/src/__tests__/server/repositories/clickhouse-helpers";
+import { pruneDatabase } from "@/src/__tests__/test-utils";
+import { getScoreById } from "@langfuse/shared/src/server";
+import { v4 } from "uuid";
+
+const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+describe("Clickhouse Scores Repository Test", () => {
+ beforeEach(async () => {
+ await pruneDatabase();
+ });
+
+ it("should return null if no scores are found", async () => {
+ const result = await getScoreById(projectId, v4());
+ expect(result).toBeUndefined();
+ });
+
+ it("should return a score if it exists", async () => {
+ const scoreId = v4();
+
+ // Assuming createScore is a helper function to insert a score into the database
+ const score = {
+ id: scoreId,
+ project_id: projectId,
+ trace_id: v4(),
+ name: "Test Score",
+ timestamp: Date.now(),
+ value: 100,
+ source: "API",
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ is_deleted: 0,
+ };
+
+ await createScores([score]);
+
+ const result = await getScoreById(projectId, scoreId);
+ expect(result).not.toBeNull();
+ if (!result) {
+ return;
+ }
+ expect(result.id).toEqual(score.id);
+ expect(result.projectId).toEqual(score.project_id);
+ expect(result.name).toEqual(score.name);
+ expect(result.value).toEqual(score.value);
+ expect(result.source).toEqual(score.source);
+ expect(result.createdAt).toBeInstanceOf(Date);
+ expect(result.updatedAt).toBeInstanceOf(Date);
+ });
+});
diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].ts
index 644aa7c9bb..93a57ca4fb 100644
--- a/web/src/pages/api/public/scores/[scoreId].ts
+++ b/web/src/pages/api/public/scores/[scoreId].ts
@@ -1,6 +1,7 @@
import { env } from "@/src/env.mjs";
import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";
import {
DeleteScoreQuery,
DeleteScoreResponse,
@@ -10,7 +11,12 @@ import {
LangfuseNotFoundError,
} from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
-import { deleteScore, traceException } from "@langfuse/shared/src/server";
+import {
+ deleteScore,
+ getScoreById,
+ logger,
+ traceException,
+} from "@langfuse/shared/src/server";
export default withMiddlewares({
GET: createAuthedAPIRoute({
@@ -20,10 +26,20 @@ export default withMiddlewares({
fn: async ({ query, auth }) => {
const { scoreId } = query;
- const score = await prisma.score.findUnique({
- where: {
- id: scoreId,
- projectId: auth.scope.projectId,
+ const score = await measureAndReturnApi({
+ input: { projectId: auth.scope.projectId, queryClickhouse: false },
+ operation: "api/public/scores/[scoreId]",
+ user: null,
+ pgExecution: async () => {
+ return await prisma.score.findUnique({
+ where: {
+ id: scoreId,
+ projectId: auth.scope.projectId,
+ },
+ });
+ },
+ clickhouseExecution: async () => {
+ return await getScoreById(auth.scope.projectId, scoreId);
},
});
@@ -35,6 +51,7 @@ export default withMiddlewares({
if (!parsedScore.success) {
traceException(parsedScore.error);
+ logger.error(`Incorrect score return type ${parsedScore.error}`);
throw new InternalServerError("Requested score is corrupted");
}