🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: support scores list endpoint from clickhouse (#4400)
Max Deichmannc438e89bd067
diff --git a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.tsindex 0297db7206..9995c06fd4 100644--- a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts@@ -4,7 +4,9 @@ import { clickhouseCompliantRandomCharacters } from "../../repositories";export interface Filter {apply(): ClickhouseFilter;clickhouseTable: string;- operator: (typeof filterOperators)[keyof typeof filterOperators][number];+ operator:+ | (typeof filterOperators)[keyof typeof filterOperators][number]+ | "!=";field: string;}type ClickhouseFilter = {@@ -69,13 +71,13 @@ export class NumberFilter implements Filter {public clickhouseTable: string;public field: string;public value: number;- public operator: (typeof filterOperators)["number"][number];+ public operator: (typeof filterOperators)["number"][number] | "!=";protected tablePrefix?: string;constructor(opts: {clickhouseTable: string;field: string;- operator: (typeof filterOperators)["number"][number];+ operator: (typeof filterOperators)["number"][number] | "!=";value: number;tablePrefix?: string;}) {@@ -256,7 +258,7 @@ export class ArrayOptionsFilter implements Filter {query = `hasAny({${varName}: Array(String)}, ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = False`;break;case "all of":- query = `arrayAll(x -> has({${varName}: Array(String)}, x), ${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}) = True`;+ query = `hasAll(${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}, {${varName}: Array(String)}) = True`;break;default:throw new Error(`Unsupported operator: ${this.operator}`);@@ -300,13 +302,13 @@ export class NumberObjectFilter implements Filter {public field: string;public key: string;public value: number;- public operator: (typeof filterOperators)["numberObject"][number];+ public operator: (typeof filterOperators)["numberObject"][number] | "!=";protected tablePrefix?: string;constructor(opts: {clickhouseTable: string;field: string;- operator: (typeof filterOperators)["numberObject"][number];+ operator: (typeof filterOperators)["numberObject"][number] | "!=";key: string;value: number;tablePrefix?: string;@@ -364,7 +366,7 @@ export class BooleanFilter implements Filter {export class FilterList {private filters: Filter[];- constructor(filters: Filter[]) {+ constructor(filters: Filter[] = []) {this.filters = filters;}@@ -376,6 +378,10 @@ export class FilterList {return this.filters.find(predicate);}+ length() {+ return this.filters.length;+ }+public apply(): ClickhouseFilter {if (this.filters.length === 0) {return {diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex b2d4f66373..f755d4aa5a 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -129,8 +129,8 @@ export const scoreRecordBaseSchema = z.object({project_id: z.string(),trace_id: z.string(),observation_id: z.string().nullish(),- name: z.string().nullish(),- value: z.union([z.number(), z.string()]).nullish(),+ name: z.string(),+ value: z.number().nullish(),source: z.string(),comment: z.string().nullish(),author_user_id: z.string().nullish(),diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.tsindex 61654a712c..3de639b6b1 100644--- a/packages/shared/src/server/repositories/scores.ts+++ b/packages/shared/src/server/repositories/scores.ts@@ -24,28 +24,7 @@ import {} from "./scores_converters";import { SCORE_TO_TRACE_OBSERVATIONS_INTERVAL } from "./constants";import { convertDateToClickhouseDateTime } from "../clickhouse/client";--export type FetchScoresReturnType = {- id: string;- timestamp: string;- project_id: string;- trace_id: string;- observation_id: string | null;- name: string;- value: number;- source: string;- comment: string | null;- author_user_id: string | null;- config_id: string | null;- data_type: string;- string_value: string | null;- queue_id: string | null;- created_at: string;- updated_at: string;- event_ts: string;- is_deleted: number;- projectId: string;-};+import { ScoreRecordReadType } from "./definitions";export const searchExistingAnnotationScore = async (projectId: string,@@ -74,7 +53,7 @@ export const searchExistingAnnotationScore = async (LIMIT 1`;- const rows = await queryClickhouse<FetchScoresReturnType>({+ const rows = await queryClickhouse<ScoreRecordReadType>({query,params: {projectId,@@ -103,7 +82,7 @@ export const getScoreById = async (LIMIT 1`;- const rows = await queryClickhouse<FetchScoresReturnType>({+ const rows = await queryClickhouse<ScoreRecordReadType>({query,params: {projectId,@@ -118,13 +97,13 @@ export const getScoreById = async (* Accepts a score in a Clickhouse-ready format.* id, project_id, name, and timestamp must always be provided.*/-export const upsertScore = async (score: Partial<FetchScoresReturnType>) => {+export const upsertScore = async (score: Partial<ScoreRecordReadType>) => {if (!["id", "project_id", "name", "timestamp"].every((key) => key in score)) {throw new Error("Identifier fields must be provided to upsert Score.");}await upsertClickhouse({table: "scores",- records: [score as FetchScoresReturnType],+ records: [score as ScoreRecordReadType],eventBodyMapper: convertToScore,});};@@ -148,7 +127,7 @@ export const getScoresForTraces = async (${limit && offset ? `limit {limit: Int32} offset {offset: Int32}` : ""}`;- const rows = await queryClickhouse<FetchScoresReturnType>({+ const rows = await queryClickhouse<ScoreRecordReadType>({query: query,params: {projectId,@@ -181,7 +160,7 @@ export const getScoresForObservations = async (${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}`;- const rows = await queryClickhouse<FetchScoresReturnType>({+ const rows = await queryClickhouse<ScoreRecordReadType>({query: query,params: {projectId: projectId,diff --git a/packages/shared/src/server/repositories/scores_converters.ts b/packages/shared/src/server/repositories/scores_converters.tsindex 8195e9d68d..7688b73aba 100644--- a/packages/shared/src/server/repositories/scores_converters.ts+++ b/packages/shared/src/server/repositories/scores_converters.ts@@ -1,5 +1,5 @@import { ScoreSource, ScoreDataType } from "@prisma/client";-import { FetchScoresReturnType } from "./scores";+import { ScoreRecordReadType } from "./definitions";export type ScoreAggregation = {id: string;@@ -11,22 +11,22 @@ export type ScoreAggregation = {comment: string | null;};-export const convertToScore = (row: FetchScoresReturnType) => {+export const convertToScore = (row: ScoreRecordReadType) => {return {id: row.id,timestamp: new Date(row.timestamp),projectId: row.project_id,traceId: row.trace_id,- observationId: row.observation_id,+ observationId: row.observation_id ?? null,name: row.name,- value: row.value,+ value: row.value ?? null,source: row.source as ScoreSource,- comment: row.comment,- authorUserId: row.author_user_id,- configId: row.config_id,+ comment: row.comment ?? null,+ authorUserId: row.author_user_id ?? null,+ configId: row.config_id ?? null,dataType: row.data_type as ScoreDataType,- stringValue: row.string_value,- queueId: row.queue_id,+ stringValue: row.string_value ?? null,+ queueId: row.queue_id ?? null,createdAt: new Date(row.created_at),updatedAt: new Date(row.updated_at),};diff --git a/web/src/__tests__/async/scores-api.servertest.ts b/web/src/__tests__/async/scores-api.servertest.tsindex da1a993681..2ecca83461 100644--- a/web/src/__tests__/async/scores-api.servertest.ts+++ b/web/src/__tests__/async/scores-api.servertest.ts@@ -1,13 +1,27 @@-import { createScores } from "@/src/__tests__/server/repositories/clickhouse-helpers";-import { makeZodVerifiedAPICall } from "@/src/__tests__/test-utils";-import { GetScoreResponse } from "@langfuse/shared";+import {+ createObservation,+ createScore,+ createTrace,+} from "@/src/__tests__/fixtures/tracing-factory";+import {+ createObservations,+ createScores,+ createTraces,+} from "@/src/__tests__/server/repositories/clickhouse-helpers";+import {+ createOrgProjectAndApiKey,+ makeZodVerifiedAPICall,+} from "@/src/__tests__/test-utils";+import { GetScoreResponse, GetScoresResponse } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";import { v4 } from "uuid";--const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";+import { z } from "zod";describe("/api/public/scores API Endpoint", () => {describe("GET /api/public/scores/:scoreId", () => {it("should GET a score", async () => {+ const { projectId: projectId, auth } = await createOrgProjectAndApiKey();+const scoreId = v4();const traceId = v4();const score = {@@ -33,6 +47,8 @@ describe("/api/public/scores API Endpoint", () => {GetScoreResponse,"GET",`/api/public/scores/${scoreId}`,+ undefined,+ auth,);expect(getScore.status).toBe(200);@@ -49,3 +65,653 @@ describe("/api/public/scores API Endpoint", () => {});});});++describe("/api/public/scores API Endpoint", () => {+ it("should create score for a trace", async () => {+ const traceId = v4();++ const { projectId: projectId, auth } = await createOrgProjectAndApiKey();++ const trace = createTrace({+ id: traceId,+ project_id: projectId,+ });+ await createTraces([trace]);++ const scoreId = v4();++ const score = createScore({+ id: scoreId,+ project_id: projectId,+ trace_id: traceId,+ name: "score-name",+ value: 100.5,+ source: "API",+ comment: "comment",+ observation_id: null,+ });+ await createScores([score]);++ const fetchedScore = await makeZodVerifiedAPICall(+ GetScoreResponse,+ "GET",+ `/api/public/scores/${scoreId}`,+ undefined,+ auth,+ );++ expect(fetchedScore.body?.id).toBe(scoreId);+ expect(fetchedScore.body?.traceId).toBe(traceId);+ expect(fetchedScore.body?.name).toBe("score-name");+ expect(fetchedScore.body?.value).toBe(100.5);+ expect(fetchedScore.body?.observationId).toBeNull();+ expect(fetchedScore.body?.comment).toBe("comment");+ expect(fetchedScore.body?.source).toBe("API");+ expect(fetchedScore.body?.projectId).toBe(projectId);+ });+ it("should GET score with minimal score data and minimal trace data", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();++ const minimalTraceId = v4();++ const trace = createTrace({+ id: minimalTraceId,+ project_id: projectId,+ });+ await createTraces([trace]);++ const minimalScoreId = v4();++ const score = createScore({+ id: minimalScoreId,+ project_id: projectId,+ trace_id: minimalTraceId,+ name: "score-name",+ value: 100.5,+ source: "API",+ comment: null,+ observation_id: null,+ });+ await createScores([score]);++ const fetchedScore = await makeZodVerifiedAPICall(+ GetScoreResponse,+ "GET",+ `/api/public/scores/${minimalScoreId}`,+ undefined,+ auth,+ );++ expect(fetchedScore.status).toBe(200);+ });+ describe("should Filter scores", () => {+ let configId = "";+ const userId = "user-name";+ const traceTags = ["prod", "test"];+ const traceTags_2 = ["staging", "dev"];+ const scoreName = "score-name";+ const queryUserName = `userId=${userId}&name=${scoreName}`;+ const traceId = v4();+ const traceId_2 = v4();+ const traceId_3 = v4();+ const generationId = v4();+ const scoreId_1 = v4();+ const scoreId_2 = v4();+ const scoreId_3 = v4();+ const scoreId_4 = v4();+ const scoreId_5 = v4();+ let authentication: string;+ let newProjectId: string;++ beforeEach(async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ authentication = auth;+ newProjectId = projectId;++ const trace = createTrace({+ id: traceId,+ project_id: newProjectId,+ user_id: userId,+ tags: traceTags,+ });++ const trace_2 = createTrace({+ id: traceId_2,+ project_id: newProjectId,+ user_id: userId,+ tags: traceTags_2,+ });++ const trace_3 = createTrace({+ id: traceId_3,+ project_id: newProjectId,+ user_id: userId,+ tags: ["staging"],+ });++ await createTraces([trace, trace_2, trace_3]);++ const generation = createObservation({+ id: generationId,+ project_id: newProjectId,+ type: "GENERATION",+ });++ await createObservations([generation]);++ const config = await prisma.scoreConfig.create({+ data: {+ name: scoreName,+ dataType: "NUMERIC",+ maxValue: 100,+ projectId: newProjectId,+ },+ });++ configId = config.id;++ const score1 = createScore({+ id: scoreId_1,+ project_id: newProjectId,+ trace_id: traceId,+ name: scoreName,+ value: 10.5,+ data_type: "NUMERIC",+ observation_id: generationId,+ config_id: config.id,+ comment: "comment",+ });++ const score2 = createScore({+ id: scoreId_2,+ project_id: newProjectId,+ trace_id: traceId,+ name: scoreName,+ value: 50.5,+ data_type: "NUMERIC",+ observation_id: generationId,+ comment: "comment",+ });++ const score3 = createScore({+ id: scoreId_3,+ project_id: newProjectId,+ trace_id: traceId,+ name: scoreName,+ value: 100.8,+ data_type: "NUMERIC",+ observation_id: generationId,+ comment: "comment",+ });++ const score4 = createScore({+ id: scoreId_4,+ project_id: newProjectId,+ trace_id: traceId_2,+ name: "other-score-name",+ value: 0,+ string_value: "best",+ data_type: "CATEGORICAL",+ comment: "comment",+ });++ const score5 = createScore({+ id: scoreId_5,+ project_id: newProjectId,+ trace_id: traceId_3,+ name: "other-score-name",+ value: 0,+ data_type: "CATEGORICAL",+ string_value: "test",+ comment: "comment",+ });++ await createScores([score1, score2, score3, score4, score5]);+ });++ it("get all scores", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?${queryUserName}`,+ undefined,+ authentication,+ );+ 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("get all scores for config", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?configId=${configId}`,+ undefined,+ authentication,+ );++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 1,+ totalPages: 1,+ });+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId,+ observationId: generationId,+ configId: configId,+ });+ }+ });++ it("get all scores for numeric data type", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?dataType=NUMERIC`,+ undefined,+ authentication,+ );++ 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,+ dataType: "NUMERIC",+ });+ }+ });++ it("get all scores for trace tag 'prod'", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?traceTags=prod`,+ undefined,+ authentication,+ );++ 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,+ trace: { tags: ["prod", "test"], userId: "user-name" },+ });+ }+ });++ it("get all scores for trace tags 'staging' and 'dev'", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?traceTags=${["staging", "dev"]}`,+ undefined,+ authentication,+ );++ expect(getAllScore.status).toBe(200);+ expect(getAllScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 1,+ totalPages: 1,+ });+ for (const val of getAllScore.body.data) {+ expect(val).toMatchObject({+ traceId: traceId_2,+ trace: {+ tags: expect.arrayContaining(["dev", "staging"]),+ userId: "user-name",+ },+ });+ }+ });++ describe("should Filter scores by queueId", () => {+ describe("queueId filtering", () => {+ let queueId: string;++ beforeEach(async () => {+ queueId = v4();+ const score = createScore({+ id: v4(),+ project_id: newProjectId,+ trace_id: traceId,+ name: "score-name",+ value: 100.5,+ source: "ANNOTATION",+ comment: "comment",+ observation_id: generationId,+ queue_id: queueId,+ });+ const score2 = createScore({+ id: v4(),+ project_id: newProjectId,+ trace_id: traceId,+ name: "score-name",+ value: 75.0,+ source: "ANNOTATION",+ comment: "comment",+ observation_id: generationId,+ queue_id: queueId,+ });++ await createScores([score, score2]);+ });++ it("get all scores for queueId", async () => {+ const getAllScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?queueId=${queueId}`,+ 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({+ traceId: traceId,+ observationId: generationId,+ queueId: queueId,+ source: "ANNOTATION",+ });+ }+ });+ });+ });++ it("test only operator", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?${queryUserName}&operator=<`,+ undefined,+ authentication,+ );+ 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 makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?${queryUserName}&value=0.8`,+ undefined,+ authentication,+ );+ 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 makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?${queryUserName}&operator=<&value=50`,+ undefined,+ authentication,+ );+ 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 makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?${queryUserName}&operator=>&value=100`,+ undefined,+ authentication,+ );+ 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 makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?${queryUserName}&operator=<=&value=50.5`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 2,+ totalPages: 1,+ });+ expect(getScore.body.data).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: scoreId_2,+ name: scoreName,+ value: 50.5,+ }),+ expect.objectContaining({+ id: scoreId_1,+ name: scoreName,+ value: 10.5,+ }),+ ]),+ );+ });+ it("test operator >=", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?${queryUserName}&operator=>=&value=50.5`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 2,+ totalPages: 1,+ });+ expect(getScore.body.data).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: scoreId_3,+ name: scoreName,+ value: 100.8,+ }),+ expect.objectContaining({+ id: scoreId_2,+ name: scoreName,+ value: 50.5,+ }),+ ]),+ );+ });+ it("test operator !=", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?${queryUserName}&operator=!=&value=50.5`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 2,+ totalPages: 1,+ });+ expect(getScore.body.data).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: scoreId_3,+ name: scoreName,+ value: 100.8,+ }),+ expect.objectContaining({+ id: scoreId_1,+ name: scoreName,+ value: 10.5,+ }),+ ]),+ );+ });+ it("test operator =", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?${queryUserName}&operator==&value=50.5`,+ undefined,+ authentication,+ );+ 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 () => {+ try {+ await makeZodVerifiedAPICall(+ z.object({+ message: z.string(),+ error: z.array(z.object({})),+ }),+ "GET",+ `/api/public/scores?${queryUserName}&operator=op&value=50.5`,+ undefined,+ authentication,+ );+ } catch (error) {+ expect((error as Error).message).toBe(+ `API call did not return 200, returned status 400, body {\"message\":\"Invalid request data\",\"error\":[{\"received\":\"op\",\"code\":\"invalid_enum_value\",\"options\":[\"<\",\">\",\"<=\",\">=\",\"!=\",\"=\"],\"path\":[\"operator\"],\"message\":\"Invalid enum value. Expected '<' | '>' | '<=' | '>=' | '!=' | '=', received 'op'\"}]}`,+ );+ }+ });+ it("test invalid value", async () => {+ try {+ await makeZodVerifiedAPICall(+ z.object({+ message: z.string(),+ error: z.array(z.object({})),+ }),+ "GET",+ `/api/public/scores?${queryUserName}&operator=<&value=myvalue`,+ undefined,+ authentication,+ );+ } catch (error) {+ expect((error as Error).message).toBe(+ 'API call did not return 200, returned status 400, body {"message":"Invalid request data","error":[{"code":"invalid_type","expected":"number","received":"nan","path":["value"],"message":"Expected number, received nan"}]}',+ );+ }+ });++ it("should filter scores by score IDs", async () => {+ const getScore = await makeZodVerifiedAPICall(+ GetScoresResponse,+ "GET",+ `/api/public/scores?scoreIds=${scoreId_1},${scoreId_2}`,+ undefined,+ authentication,+ );+ expect(getScore.status).toBe(200);+ expect(getScore.body.meta).toMatchObject({+ page: 1,+ limit: 50,+ totalItems: 2,+ totalPages: 1,+ });+ expect(getScore.body.data).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: scoreId_2,+ name: scoreName,+ value: 50.5,+ }),+ expect.objectContaining({+ id: scoreId_1,+ name: scoreName,+ value: 10.5,+ }),+ ]),+ );+ });+ });+});diff --git a/web/src/__tests__/scores.servertest.ts b/web/src/__tests__/scores.servertest.tsindex ea541060d1..a23b65175b 100644--- a/web/src/__tests__/scores.servertest.ts+++ b/web/src/__tests__/scores.servertest.ts@@ -7,12 +7,7 @@ import {pruneDatabase,} from "@/src/__tests__/test-utils";import { v4 as uuidv4 } from "uuid";-import {- DeleteScoreResponse,- GetScoreResponse,- GetScoresResponse,-} from "@langfuse/shared";-import { z } from "zod";+import { DeleteScoreResponse, GetScoreResponse } from "@langfuse/shared";import { PostTracesV1Response } from "@/src/features/public-api/types/traces";const traceId = "de98afa2-89dc-47e9-9924-33f1490fdaf4";@@ -111,39 +106,6 @@ 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();@@ -826,573 +788,4 @@ describe("/api/public/scores API Endpoint", () => {});expect(deletedScore).toBeNull();});-- describe("should Filter scores", () => {- let configId = "";- const userId = "user-name";- const traceTags = ["prod", "test"];- const traceTags_2 = ["staging", "dev"];- const scoreName = "score-name";- const queryUserName = `userId=${userId}&name=${scoreName}`;- const traceId = uuidv4();- const traceId_2 = uuidv4();- const traceId_3 = uuidv4();- const generationId = uuidv4();- const scoreId_1 = uuidv4();- const scoreId_2 = uuidv4();- const scoreId_3 = uuidv4();- const scoreId_4 = uuidv4();- const scoreId_5 = uuidv4();-- beforeAll(async () => {- should_prune_db = false;- await pruneDatabase();-- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId,- userId: userId,- tags: traceTags,- },- );- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId_2,- userId: userId,- tags: traceTags_2,- },- );- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/traces",- {- id: traceId_3,- userId: userId,- tags: ["staging"],- },- );- await makeZodVerifiedAPICall(- PostTracesV1Response,- "POST",- "/api/public/generations",- {- id: generationId,- },- );-- await makeAPICall("POST", "/api/public/score-configs", {- name: scoreName,- dataType: "NUMERIC",- maxValue: 100,- });-- const config = await prisma.scoreConfig.findFirst({- where: {- name: scoreName,- },- });- configId = config?.id ?? "";-- await makeAPICall("POST", "/api/public/scores", {- id: scoreId_1,- observationId: generationId,- name: scoreName,- value: 10.5,- traceId: traceId,- comment: "comment",- configId,- });- 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",- });- await makeAPICall("POST", "/api/public/scores", {- id: scoreId_4,- name: "other-score-name",- value: "best",- traceId: traceId_2,- comment: "comment",- });- await makeAPICall("POST", "/api/public/scores", {- id: scoreId_5,- name: "other-score-name",- value: "test",- traceId: traceId_3,- comment: "comment",- });- });- afterAll(async () => {- await pruneDatabase();- });-- it("get all scores", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "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("get all scores for config", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/scores?configId=${configId}`,- );-- expect(getAllScore.status).toBe(200);- expect(getAllScore.body.meta).toMatchObject({- page: 1,- limit: 50,- totalItems: 1,- totalPages: 1,- });- for (const val of getAllScore.body.data) {- expect(val).toMatchObject({- traceId: traceId,- observationId: generationId,- configId: configId,- });- }- });-- it("get all scores for numeric data type", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/scores?dataType=${"NUMERIC"}`,- );-- 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,- dataType: "NUMERIC",- });- }- });-- it("get all scores for trace tag 'prod'", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/scores?traceTags=${"prod"}`,- );-- 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,- trace: { tags: ["prod", "test"], userId: "user-name" },- });- }- });-- it("get all scores for trace tags 'staging' and 'dev'", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/scores?traceTags=${["staging", "dev"]}`,- );-- expect(getAllScore.status).toBe(200);- expect(getAllScore.body.meta).toMatchObject({- page: 1,- limit: 50,- totalItems: 1,- totalPages: 1,- });- for (const val of getAllScore.body.data) {- expect(val).toMatchObject({- traceId: traceId_2,- trace: { tags: ["dev", "staging"], userId: "user-name" },- });- }- });-- describe("should Filter scores by queueId", () => {- describe("queueId filtering", () => {- let queueId: string;- const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";-- beforeEach(async () => {- queueId = uuidv4();-- await Promise.all([- prisma.score.create({- data: {- observationId: generationId,- name: "annotation-score-1",- value: 100.5,- traceId: traceId,- comment: "comment 1",- queueId,- source: "ANNOTATION",- project: { connect: { id: projectId } },- dataType: "NUMERIC",- },- }),- prisma.score.create({- data: {- observationId: generationId,- name: "annotation-score-2",- value: 75.0,- traceId: traceId,- comment: "comment 2",- queueId,- source: "ANNOTATION",- project: { connect: { id: projectId } },- dataType: "NUMERIC",- },- }),- ]);- });-- afterEach(async () => {- await prisma.score.deleteMany({- where: { queueId, projectId },- });- });-- it("get all scores for queueId", async () => {- const getAllScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/scores?queueId=${queueId}`,- );-- 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({- traceId: traceId,- observationId: generationId,- queueId: queueId,- source: "ANNOTATION",- });- }- });- });- });-- it("test only operator", async () => {- const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "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 makeZodVerifiedAPICall(- GetScoresResponse,- "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 makeZodVerifiedAPICall(- GetScoresResponse,- "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 makeZodVerifiedAPICall(- GetScoresResponse,- "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 makeZodVerifiedAPICall(- GetScoresResponse,- "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_1,- name: scoreName,- value: 10.5,- },- ]);- });- it("test operator >=", async () => {- const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "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_3,- name: scoreName,- value: 100.8,- },- {- id: scoreId_2,- name: scoreName,- value: 50.5,- },- ]);- });- it("test operator !=", async () => {- const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "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_3,- name: scoreName,- value: 100.8,- },- {- id: scoreId_1,- name: scoreName,- value: 10.5,- },- ]);- });- it("test operator =", async () => {- const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "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("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: 6,- totalPages: 1,- });- expect(fetchedScores.body.data.length).toBe(6);- });-- it("test invalid operator", async () => {- try {- await makeZodVerifiedAPICall(- z.object({- message: z.string(),- error: z.array(z.object({})),- }),- "GET",- `/api/public/scores?${queryUserName}&operator=op&value=50.5`,- );- } catch (error) {- expect((error as Error).message).toBe(- `API call did not return 200, returned status 400, body {\"message\":\"Invalid request data\",\"error\":[{\"received\":\"op\",\"code\":\"invalid_enum_value\",\"options\":[\"<\",\">\",\"<=\",\">=\",\"!=\",\"=\"],\"path\":[\"operator\"],\"message\":\"Invalid enum value. Expected '<' | '>' | '<=' | '>=' | '!=' | '=', received 'op'\"}]}`,- );- }- });- it("test invalid value", async () => {- try {- await makeZodVerifiedAPICall(- z.object({- message: z.string(),- error: z.array(z.object({})),- }),- "GET",- `/api/public/scores?${queryUserName}&operator=<&value=myvalue`,- );- } catch (error) {- expect((error as Error).message).toBe(- 'API call did not return 200, returned status 400, body {"message":"Invalid request data","error":[{"code":"invalid_type","expected":"number","received":"nan","path":["value"],"message":"Expected number, received nan"}]}',- );- }- });-- it("should filter scores by score IDs", async () => {- const getScore = await makeZodVerifiedAPICall(- GetScoresResponse,- "GET",- `/api/public/scores?scoreIds=${scoreId_1},${scoreId_2}`,- );- 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_1,- name: scoreName,- value: 10.5,- },- ]);- });- });});diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex 46c8b10ee8..1400f397be 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -1,6 +1,11 @@import { env } from "@/src/env.mjs";import { prisma } from "@langfuse/shared/src/db";-import { clickhouseClient } from "@langfuse/shared/src/server";+import {+ clickhouseClient,+ getDisplaySecretKey,+ hashSecretKey,+} from "@langfuse/shared/src/server";+import { v4 } from "uuid";import { type z } from "zod";export const pruneDatabase = async () => {@@ -38,7 +43,10 @@ export const pruneDatabase = async () => {});};-function createBasicAuthHeader(username: string, password: string): string {+export function createBasicAuthHeader(+ username: string,+ password: string,+): string {const base64Credentials = Buffer.from(`${username}:${password}`).toString("base64",);@@ -130,3 +138,35 @@ export async function makeZodVerifiedAPICallSilent<T extends z.ZodTypeAny>(return { body: resBody, status };}++export const createOrgProjectAndApiKey = async () => {+ const projectId = v4();+ const org = await prisma.organization.create({+ data: {+ id: v4(),+ name: v4(),+ },+ });+ await prisma.project.create({+ data: {+ id: projectId,+ name: v4(),+ orgId: org.id,+ },+ });+ const publicKey = v4();+ const secretKey = v4();++ const auth = createBasicAuthHeader(publicKey, secretKey);+ await prisma.apiKey.create({+ data: {+ id: v4(),+ projectId: projectId,+ publicKey: publicKey,+ hashedSecretKey: await hashSecretKey(secretKey),+ displaySecretKey: getDisplaySecretKey(secretKey),+ },+ });++ return { projectId, publicKey, secretKey, auth };+};diff --git a/web/src/features/datasets/server/service.ts b/web/src/features/datasets/server/service.tsindex cea984cf61..5a4c041002 100644--- a/web/src/features/datasets/server/service.ts+++ b/web/src/features/datasets/server/service.ts@@ -13,7 +13,6 @@ import {clickhouseCompliantRandomCharacters,commandClickhouse,convertToScore,- type FetchScoresReturnType,getLatencyAndTotalCostForObservations,getLatencyAndTotalCostForObservationsByTraces,getObservationsById,@@ -22,6 +21,7 @@ import {getTracesByIds,logger,queryClickhouse,+ type ScoreRecordReadType,traceException,} from "@langfuse/shared/src/server";import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";@@ -242,9 +242,7 @@ const getScoresFromTempTable = async (SETTINGS select_sequential_consistency = 1;`;- const rows = await queryClickhouse<- FetchScoresReturnType & { run_id: string }- >({+ const rows = await queryClickhouse<ScoreRecordReadType & { run_id: string }>({query: query,params: {projectId: input.projectId,diff --git a/web/src/features/public-api/server/sores.ts b/web/src/features/public-api/server/sores.tsnew file mode 100644index 0000000000..301390d3bf--- /dev/null+++ b/web/src/features/public-api/server/sores.ts@@ -0,0 +1,294 @@+import {+ FilterList,+ StringFilter,+ NumberFilter,+ type ScoreRecordReadType,+ queryClickhouse,+ DateTimeFilter,+ ArrayOptionsFilter,+ convertToScore,+ StringOptionsFilter,+} from "@langfuse/shared/src/server";+import { z } from "zod";++export type ScoreQueryType = {+ page: number;+ limit: number;+ projectId: string;+ traceId?: string;+ userId?: string;+ name?: string;+ source?: string;+ fromTimestamp?: string;+ toTimestamp?: string;+ value?: number;+ scoreId?: string;+ configId?: string;+ queueId?: string;+ traceTags?: string | string[];+ operator?: string;+ scoreIds?: string[];+ dataType?: string;+};++export const generateScoresForPublicApi = async (props: ScoreQueryType) => {+ const { scoresFilter, tracesFilter } = generateScoreFilter(props);+ const appliedScoresFilter = scoresFilter.apply();+ const appliedTracesFilter = tracesFilter.apply();++ const query = `+ SELECT+ s.id,+ s.timestamp,+ s.name,+ s.value,+ s.string_value,+ s.author_user_id,+ s.project_id,+ s.created_at,+ s.updated_at,+ s.source,+ s.comment,+ s.data_type,+ s.config_id,+ s.queue_id,+ s.trace_id,+ s.observation_id,+ t.user_id,+ t.tags+ FROM scores s+ JOIN traces t FINAL ON s.trace_id = t.id AND s.project_id = t.project_id+ WHERE s.project_id = {projectId: String}+ AND t.project_id = {projectId: String}+ ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}+ ${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}+ ORDER BY s.timestamp desc+ LIMIT 1 BY s.id, s.project_id+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}+ `;++ const records = await queryClickhouse<+ ScoreRecordReadType & { tags: string[]; user_id: string }+ >({+ query,+ params: {+ ...appliedScoresFilter.params,+ ...appliedTracesFilter.params,+ projectId: props.projectId,+ ...(props.limit !== undefined ? { limit: props.limit } : {}),+ ...(props.page !== undefined+ ? { offset: (props.page - 1) * props.limit }+ : {}),+ },+ });+ return records.map((record) => ({+ ...convertToScore(record),+ trace: { userId: record.user_id, tags: record.tags },+ }));+};++export const getScoresCountForPublicApi = async (props: ScoreQueryType) => {+ const { scoresFilter, tracesFilter } = generateScoreFilter(props);+ const appliedScoresFilter = scoresFilter.apply();+ const appliedTracesFilter = tracesFilter.apply();++ const query = `+ SELECT+ count() as count+ FROM scores s+ JOIN traces t FINAL ON s.trace_id = t.id AND s.project_id = t.project_id+ WHERE s.project_id = {projectId: String}+ AND t.project_id = {projectId: String}+ ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}+ ${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}+ `;++ const records = await queryClickhouse<{ count: string }>({+ query,+ params: {+ ...appliedScoresFilter.params,+ ...appliedTracesFilter.params,+ projectId: props.projectId,+ },+ });+ return records.map((record) => Number(record.count)).shift();+};++const generateScoreFilter = (filter: ScoreQueryType) => {+ const scoresFilter = new FilterList([+ new StringFilter({+ clickhouseTable: "scores",+ field: "project_id",+ operator: "=",+ value: filter.projectId,+ }),+ ]);++ const tracesFilter = new FilterList();++ const secureFilterOptions = [+ {+ key: "userId",+ field: "user_id",+ table: "traces",+ filterType: "StringFilter",+ },+ {+ key: "traceId",+ field: "trace_id",+ table: "scores",+ filterType: "StringFilter",+ },+ { key: "name", field: "name", table: "scores", filterType: "StringFilter" },+ {+ key: "source",+ field: "source",+ table: "scores",+ filterType: "StringFilter",+ },+ {+ key: "fromTimestamp",+ field: "timestamp",+ isDate: true,+ operator: ">=" as const,+ table: "scores",+ filterType: "DateTimeFilter",+ },+ {+ key: "toTimestamp",+ field: "timestamp",+ isDate: true,+ operator: "<" as const,+ table: "scores",+ filterType: "DateTimeFilter",+ },+ {+ key: "value",+ field: "value",+ table: "scores",+ filterType: "NumberFilter",+ },+ {+ key: "scoreIds",+ field: "id",+ table: "scores",+ filterType: "StringOptionsFilter",+ },+ {+ key: "configId",+ field: "config_id",+ table: "scores",+ filterType: "StringFilter",+ },+ {+ key: "queueId",+ field: "queue_id",+ table: "scores",+ filterType: "StringFilter",+ },+ {+ key: "traceTags",+ field: "tags",+ isArray: true,+ table: "traces",+ filterType: "ArrayOptionsFilter",+ },+ {+ key: "dataType",+ field: "data_type",+ table: "scores",+ filterType: "StringFilter",+ },+ ];++ secureFilterOptions.forEach((secureFilterOption) => {+ const value = filter[secureFilterOption.key as keyof ScoreQueryType];++ if (value) {+ let filterInstance;+ switch (secureFilterOption.filterType) {+ case "DateTimeFilter":+ const availableOperators = z.enum(["=", ">", "<", ">=", "<=", "!="]);+ typeof value === "string" &&+ secureFilterOption.operator &&+ availableOperators.safeParse(secureFilterOption.operator).success+ ? (filterInstance = new DateTimeFilter({+ clickhouseTable: secureFilterOption.table,+ field: secureFilterOption.field,+ operator: secureFilterOption.operator,+ value: new Date(value),+ tablePrefix: secureFilterOption.table === "scores" ? "s" : "t",+ }))+ : undefined;++ break;+ case "ArrayOptionsFilter":+ if (Array.isArray(value) || typeof value === "string") {+ filterInstance = new ArrayOptionsFilter({+ clickhouseTable: secureFilterOption.table,+ field: secureFilterOption.field,+ operator: "all of",+ values: Array.isArray(value) ? value : value.split(","),+ tablePrefix: secureFilterOption.table === "scores" ? "s" : "t",+ });+ }+ break;+ case "StringOptionsFilter":+ if (Array.isArray(value) || typeof value === "string") {+ filterInstance = new StringOptionsFilter({+ clickhouseTable: secureFilterOption.table,+ field: secureFilterOption.field,+ operator: "any of",+ values: Array.isArray(value) ? value : value.split(","),+ tablePrefix: secureFilterOption.table === "scores" ? "s" : "t",+ });+ }+ break;+ case "StringFilter":+ if (typeof value === "string") {+ filterInstance = new StringFilter({+ clickhouseTable: secureFilterOption.table,+ field: secureFilterOption.field,+ operator: "=",+ value: value,+ tablePrefix: secureFilterOption.table === "scores" ? "s" : "t",+ });+ }+ break;+ case "NumberFilter":+ const availableOperatorsNum = z.enum([+ "=",+ ">",+ "<",+ ">=",+ "<=",+ "!=",+ ]);+ const parsedOperator = availableOperatorsNum.safeParse(+ filter.operator,+ );++ if (parsedOperator.success) {+ filterInstance = new NumberFilter({+ clickhouseTable: secureFilterOption.table,+ field: secureFilterOption.field,+ operator: parsedOperator.data,+ value: Number(value),+ tablePrefix: secureFilterOption.table === "scores" ? "s" : "t",+ });+ }+ break;+ }++ if (filterInstance) {+ if (secureFilterOption.table === "scores") {+ scoresFilter.push(filterInstance);+ } else if (secureFilterOption.table === "traces") {+ tracesFilter.push(filterInstance);+ }+ }+ }+ });++ return { scoresFilter, tracesFilter };+};diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.tsindex a020faba47..32fd56709d 100644--- a/web/src/pages/api/public/observations/index.ts+++ b/web/src/pages/api/public/observations/index.ts@@ -191,6 +191,7 @@ export default withMiddlewares({},}): [];+ const finalCount = count ? count : 0;return {data: items@@ -214,8 +215,8 @@ export default withMiddlewares({meta: {page: query.page,limit: query.limit,- totalItems: count ?? 0,- totalPages: Math.ceil(count ?? 0 / query.limit),+ totalItems: finalCount,+ totalPages: Math.ceil(finalCount / query.limit),},};},diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex 7bae9d3309..cd4702ffdb 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -16,6 +16,11 @@ import {processEventBatch,} from "@langfuse/shared/src/server";import { tokenCount } from "@/src/features/ingest/usage";+import { measureAndReturnApi } from "@/src/server/utils/checkClickhouseAccess";+import {+ generateScoresForPublicApi,+ getScoresCountForPublicApi,+} from "@/src/features/public-api/server/sores";export default withMiddlewares({POST: createAuthedAPIRoute({@@ -48,7 +53,7 @@ export default withMiddlewares({},}),GET: createAuthedAPIRoute({- name: "Get Scores",+ name: "/api/public/scores",querySchema: GetScoresQuery,responseSchema: GetScoresResponse,fn: async ({ query, auth }) => {@@ -69,118 +74,176 @@ export default withMiddlewares({dataType,} = query;- const skipValue = (page - 1) * limit;- const configCondition = configId- ? Prisma.sql`AND s."config_id" = ${configId}`- : Prisma.empty;- const queueCondition = queueId- ? Prisma.sql`AND s."queue_id" = ${queueId}`- : Prisma.empty;- const traceTagsCondition = traceTags- ? Prisma.sql`AND ARRAY[${Prisma.join(- (Array.isArray(traceTags) ? traceTags : traceTags.split(",")).map(- (v) => Prisma.sql`${v}`,- ),- ", ",- )}] <@ t."tags"`- : Prisma.empty;- const dataTypeCondition = dataType- ? Prisma.sql`AND s."data_type" = ${dataType}::"ScoreDataType"`- : Prisma.empty;- const userCondition = userId- ? Prisma.sql`AND t."user_id" = ${userId}`- : Prisma.empty;- const nameCondition = name- ? Prisma.sql`AND s."name" = ${name}`- : Prisma.empty;- const fromTimestampCondition = fromTimestamp- ? Prisma.sql`AND s."timestamp" >= ${fromTimestamp}::timestamp with time zone at time zone 'UTC'`- : Prisma.empty;- const toTimestampCondition = toTimestamp- ? Prisma.sql`AND s."timestamp" < ${toTimestamp}::timestamp with time zone at time zone 'UTC'`- : Prisma.empty;- const sourceCondition = source- ? Prisma.sql`AND s."source" = ${source}`- : Prisma.empty;- const valueCondition =- operator && value !== null && value !== undefined- ? Prisma.sql`AND s."value" ${Prisma.raw(`${operator}`)} ${value}`- : Prisma.empty;- const scoreIdCondition = scoreIds- ? Prisma.sql`AND s."id" = ANY(${scoreIds})`- : Prisma.empty;+ return await measureAndReturnApi({+ input: { projectId: auth.scope.projectId, queryClickhouse: false },+ operation: "api/public/observations",+ user: null,+ pgExecution: async () => {+ const skipValue = (page - 1) * limit;+ const configCondition = configId+ ? Prisma.sql`AND s."config_id" = ${configId}`+ : Prisma.empty;+ const queueCondition = queueId+ ? Prisma.sql`AND s."queue_id" = ${queueId}`+ : Prisma.empty;+ const traceTagsCondition = traceTags+ ? Prisma.sql`AND ARRAY[${Prisma.join(+ (Array.isArray(traceTags)+ ? traceTags+ : traceTags.split(",")+ ).map((v) => Prisma.sql`${v}`),+ ", ",+ )}] <@ t."tags"`+ : Prisma.empty;+ const dataTypeCondition = dataType+ ? Prisma.sql`AND s."data_type" = ${dataType}::"ScoreDataType"`+ : Prisma.empty;+ const userCondition = userId+ ? Prisma.sql`AND t."user_id" = ${userId}`+ : Prisma.empty;+ const nameCondition = name+ ? Prisma.sql`AND s."name" = ${name}`+ : Prisma.empty;+ const fromTimestampCondition = fromTimestamp+ ? Prisma.sql`AND s."timestamp" >= ${fromTimestamp}::timestamp with time zone at time zone 'UTC'`+ : Prisma.empty;+ const toTimestampCondition = toTimestamp+ ? Prisma.sql`AND s."timestamp" < ${toTimestamp}::timestamp with time zone at time zone 'UTC'`+ : Prisma.empty;+ const sourceCondition = source+ ? Prisma.sql`AND s."source" = ${source}`+ : Prisma.empty;+ const valueCondition =+ operator && value !== null && value !== undefined+ ? Prisma.sql`AND s."value" ${Prisma.raw(`${operator}`)} ${value}`+ : Prisma.empty;+ const scoreIdCondition = scoreIds+ ? Prisma.sql`AND s."id" = ANY(${scoreIds})`+ : Prisma.empty;- const scores = await prisma.$queryRaw<Array<unknown>>(Prisma.sql`- SELECT- s.id,- s.timestamp,- 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",- s.config_id as "configId",- s.queue_id as "queueId",- s.trace_id as "traceId",- s.observation_id as "observationId",- json_build_object('userId', t.user_id, 'tags', t.tags) as "trace"- FROM "scores" AS s- LEFT JOIN "traces" AS t ON t.id = s.trace_id AND t.project_id = ${auth.scope.projectId}- WHERE s.project_id = ${auth.scope.projectId}- ${configCondition}- ${queueCondition}- ${traceTagsCondition}- ${dataTypeCondition}- ${userCondition}- ${nameCondition}- ${sourceCondition}- ${fromTimestampCondition}- ${toTimestampCondition}- ${valueCondition}- ${scoreIdCondition}- ORDER BY s."timestamp" DESC- LIMIT ${limit} OFFSET ${skipValue}+ const scores = await prisma.$queryRaw<Array<unknown>>(Prisma.sql`+ SELECT+ s.id,+ s.timestamp,+ 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",+ s.config_id as "configId",+ s.queue_id as "queueId",+ s.trace_id as "traceId",+ s.observation_id as "observationId",+ json_build_object('userId', t.user_id, 'tags', t.tags) as "trace"+ FROM "scores" AS s+ LEFT JOIN "traces" AS t ON t.id = s.trace_id AND t.project_id = ${auth.scope.projectId}+ WHERE s.project_id = ${auth.scope.projectId}+ ${configCondition}+ ${queueCondition}+ ${traceTagsCondition}+ ${dataTypeCondition}+ ${userCondition}+ ${nameCondition}+ ${sourceCondition}+ ${fromTimestampCondition}+ ${toTimestampCondition}+ ${valueCondition}+ ${scoreIdCondition}+ ORDER BY s."timestamp" DESC+ LIMIT ${limit} OFFSET ${skipValue}`);- const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>(- Prisma.sql`- SELECT COUNT(*) as count- FROM "scores" AS s- LEFT JOIN "traces" AS t ON t.id = s.trace_id AND t.project_id = ${auth.scope.projectId}- WHERE s.project_id = ${auth.scope.projectId}- ${configCondition}- ${queueCondition}- ${traceTagsCondition}- ${dataTypeCondition}- ${userCondition}- ${nameCondition}- ${sourceCondition}- ${fromTimestampCondition}- ${toTimestampCondition}- ${valueCondition}- ${scoreIdCondition}- `,- );+ const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>(+ Prisma.sql`+ SELECT COUNT(*) as count+ FROM "scores" AS s+ LEFT JOIN "traces" AS t ON t.id = s.trace_id AND t.project_id = ${auth.scope.projectId}+ WHERE s.project_id = ${auth.scope.projectId}+ ${configCondition}+ ${queueCondition}+ ${traceTagsCondition}+ ${dataTypeCondition}+ ${userCondition}+ ${nameCondition}+ ${sourceCondition}+ ${fromTimestampCondition}+ ${toTimestampCondition}+ ${valueCondition}+ ${scoreIdCondition}+ `,+ );- const validatedScores = legacyFilterAndValidateV1GetScoreList(scores);+ const validatedScores = legacyFilterAndValidateV1GetScoreList(scores);- const totalItems =- totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;+ const totalItems =+ totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;- return {- data: validatedScores,- meta: {- page: page,- limit: limit,- totalItems,- totalPages: Math.ceil(totalItems / limit),+ return {+ data: validatedScores,+ meta: {+ page: page,+ limit: limit,+ totalItems,+ totalPages: Math.ceil(totalItems / limit),+ },+ };},- };+ clickhouseExecution: async () => {+ const [items, count] = await Promise.all([+ generateScoresForPublicApi({+ projectId: auth.scope.projectId,+ page: query.page ?? undefined,+ limit: query.limit ?? undefined,+ userId: query.userId ?? undefined,+ name: query.name ?? undefined,+ configId: query.configId ?? undefined,+ queueId: query.queueId ?? undefined,+ traceTags: query.traceTags ?? undefined,+ dataType: query.dataType ?? undefined,+ fromTimestamp: query.fromTimestamp ?? undefined,+ toTimestamp: query.toTimestamp ?? undefined,+ source: query.source ?? undefined,+ value: query.value ?? undefined,+ operator: query.operator ?? undefined,+ scoreIds: query.scoreIds ?? undefined,+ }),+ getScoresCountForPublicApi({+ projectId: auth.scope.projectId,+ page: query.page ?? undefined,+ limit: query.limit ?? undefined,+ userId: query.userId ?? undefined,+ name: query.name ?? undefined,+ configId: query.configId ?? undefined,+ queueId: query.queueId ?? undefined,+ traceTags: query.traceTags ?? undefined,+ dataType: query.dataType ?? undefined,+ fromTimestamp: query.fromTimestamp ?? undefined,+ toTimestamp: query.toTimestamp ?? undefined,+ source: query.source ?? undefined,+ value: query.value ?? undefined,+ operator: query.operator ?? undefined,+ scoreIds: query.scoreIds ?? undefined,+ }),+ ]);++ const finalCount = count ? count : 0;++ return {+ data: legacyFilterAndValidateV1GetScoreList(items),+ meta: {+ page: query.page,+ limit: query.limit,+ totalItems: finalCount,+ totalPages: Math.ceil(finalCount / query.limit),+ },+ };+ },+ });},}),});