Skip to content

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

feat(api): add GET /score-configs/[configId] and GET /score-configs (#2361)

marliessophie4e27b6f0f1d1
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index 30e790f912..ae3dc40310 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -111,7 +111,24 @@ types:
totalCost:
docs: USD total cost, defaults to input+output
type: optional<double>
-
+ ScoreConfig:
+ docs: Configuration for a score
+ properties:
+ id: string
+ name: string
+ createdAt: datetime
+ updatedAt: datetime
+ projectId: string
+ dataType: ScoreDataType
+ isArchived: boolean
+ minValue: optional<double>
+ maxValue: optional<double>
+ categories: optional<list<ConfigCategory>>
+ description: optional<string>
+ ConfigCategory:
+ properties:
+ value: double
+ label: string
Score:
properties:
id: string
@@ -212,6 +229,11 @@ types:
- ANNOTATION
- API
- EVAL
+ ScoreDataType:
+ enum:
+ - NUMERIC
+ - BOOLEAN
+ - CATEGORICAL
errors:
Error:
diff --git a/fern/apis/server/definition/score-configs.yml b/fern/apis/server/definition/score-configs.yml
new file mode 100644
index 0000000000..7b0323fb53
--- /dev/null
+++ b/fern/apis/server/definition/score-configs.yml
@@ -0,0 +1,36 @@
+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json
+imports:
+ pagination: ./utils/pagination.yml
+ commons: ./commons.yml
+service:
+ auth: true
+ base-path: /api/public
+ endpoints:
+ get:
+ docs: Get all score configs
+ method: GET
+ path: /score-configs
+ request:
+ name: GetScoreConfigsRequest
+ query-parameters:
+ page:
+ type: optional<integer>
+ docs: Page number, starts at 1.
+ limit:
+ type: optional<integer>
+ docs: Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit.
+ response: ScoreConfigs
+ get-by-id:
+ docs: Get a score config
+ method: GET
+ path: /score-configs/{configId}
+ path-parameters:
+ configId:
+ type: string
+ docs: The unique langfuse identifier of a score config
+ response: commons.ScoreConfig
+types:
+ ScoreConfigs:
+ properties:
+ data: list<commons.ScoreConfig>
+ meta: pagination.MetaResponse
diff --git a/packages/shared/src/features/annotation/types.ts b/packages/shared/src/features/annotation/types.ts
index c6f290c503..f414c43d2d 100644
--- a/packages/shared/src/features/annotation/types.ts
+++ b/packages/shared/src/features/annotation/types.ts
@@ -1,4 +1,5 @@
import z from "zod";
+import { ScoreConfig } from "../../db";
const configCategory = z.object({
label: z.string().min(1),
@@ -8,3 +9,7 @@ const configCategory = z.object({
export const categoriesList = z.array(configCategory);
export type ConfigCategory = z.infer<typeof configCategory>;
+
+export type CastedConfig = Omit<ScoreConfig, "categories"> & {
+ categories: ConfigCategory[] | null;
+};
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index ac821f024d..cc4ce4b23f 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -928,6 +928,108 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/CreatePromptRequest'
+ /api/public/score-configs:
+ get:
+ description: Get all score configs
+ operationId: scoreConfigs_get
+ tags:
+ - ScoreConfigs
+ parameters:
+ - name: page
+ in: query
+ description: Page number, starts at 1.
+ required: false
+ schema:
+ type: integer
+ nullable: true
+ - name: limit
+ in: query
+ description: >-
+ Limit of items per page. If you encounter api issues due to too
+ large page sizes, try to reduce the limit.
+ required: false
+ schema:
+ type: integer
+ nullable: true
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ScoreConfigs'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security: *ref_0
+ /api/public/score-configs/{configId}:
+ get:
+ description: Get a score config
+ operationId: scoreConfigs_get-by-id
+ tags:
+ - ScoreConfigs
+ parameters:
+ - name: configId
+ in: path
+ description: The unique langfuse identifier of a score config
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ScoreConfig'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security: *ref_0
/api/public/scores:
post:
description: Create a score
@@ -1625,6 +1727,63 @@ components:
format: double
nullable: true
description: USD total cost, defaults to input+output
+ ScoreConfig:
+ title: ScoreConfig
+ type: object
+ description: Configuration for a score
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ createdAt:
+ type: string
+ format: date-time
+ updatedAt:
+ type: string
+ format: date-time
+ projectId:
+ type: string
+ dataType:
+ $ref: '#/components/schemas/ScoreDataType'
+ isArchived:
+ type: boolean
+ minValue:
+ type: number
+ format: double
+ nullable: true
+ maxValue:
+ type: number
+ format: double
+ nullable: true
+ categories:
+ type: array
+ items:
+ $ref: '#/components/schemas/ConfigCategory'
+ nullable: true
+ description:
+ type: string
+ nullable: true
+ required:
+ - id
+ - name
+ - createdAt
+ - updatedAt
+ - projectId
+ - dataType
+ - isArchived
+ ConfigCategory:
+ title: ConfigCategory
+ type: object
+ properties:
+ value:
+ type: number
+ format: double
+ label:
+ type: string
+ required:
+ - value
+ - label
Score:
title: Score
type: object
@@ -1867,6 +2026,13 @@ components:
- ANNOTATION
- API
- EVAL
+ ScoreDataType:
+ title: ScoreDataType
+ type: string
+ enum:
+ - NUMERIC
+ - BOOLEAN
+ - CATEGORICAL
CreateDatasetItemRequest:
title: CreateDatasetItemRequest
type: object
@@ -2837,6 +3003,19 @@ components:
- prompt
allOf:
- $ref: '#/components/schemas/BasePrompt'
+ ScoreConfigs:
+ title: ScoreConfigs
+ type: object
+ properties:
+ data:
+ type: array
+ items:
+ $ref: '#/components/schemas/ScoreConfig'
+ meta:
+ $ref: '#/components/schemas/utilsMetaResponse'
+ required:
+ - data
+ - meta
CreateScoreRequest:
title: CreateScoreRequest
type: object
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index a5e39003fe..d0850f9bde 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -711,6 +711,81 @@
}
]
},
+ {
+ "_type": "container",
+ "description": null,
+ "name": "Score Configs",
+ "item": [
+ {
+ "_type": "endpoint",
+ "name": "Get",
+ "request": {
+ "description": "Get all score configs",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/score-configs?page=&limit=",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "score-configs"
+ ],
+ "query": [
+ {
+ "key": "page",
+ "value": "",
+ "description": "Page number, starts at 1."
+ },
+ {
+ "key": "limit",
+ "value": "",
+ "description": "Limit of items per page. If you encounter api issues due to too large page sizes, try to reduce the limit."
+ }
+ ],
+ "variable": []
+ },
+ "header": [],
+ "method": "GET",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Get By Id",
+ "request": {
+ "description": "Get a score config",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/score-configs/:configId",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "score-configs",
+ ":configId"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "configId",
+ "value": "",
+ "description": "The unique langfuse identifier of a score config"
+ }
+ ]
+ },
+ "header": [],
+ "method": "GET",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ }
+ ]
+ },
{
"_type": "container",
"description": null,
diff --git a/web/src/__tests__/score-configs.servertest.ts b/web/src/__tests__/score-configs.servertest.ts
new file mode 100644
index 0000000000..b0aa386204
--- /dev/null
+++ b/web/src/__tests__/score-configs.servertest.ts
@@ -0,0 +1,143 @@
+/** @jest-environment node */
+
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import { v4 as uuidv4 } from "uuid";
+import { ScoreDataType, prisma } from "@langfuse/shared/src/db";
+import { type CastedConfig } from "@langfuse/shared";
+
+const CONFIG_ID_ONE = uuidv4();
+const CONFIG_ID_TWO = uuidv4();
+const CONFIG_ID_THREE = uuidv4();
+
+const configOne = [
+ {
+ id: CONFIG_ID_ONE,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "Test Boolean Config",
+ description: "Test Description",
+ dataType: ScoreDataType.BOOLEAN,
+ categories: [
+ { label: "False", value: 0 },
+ { label: "True", value: 1 },
+ ],
+ createdAt: new Date("2024-05-10T00:00:00.000Z"),
+ updatedAt: new Date("2024-05-10T00:00:00.000Z"),
+ },
+];
+const configTwo = [
+ {
+ id: CONFIG_ID_TWO,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "Test Numeric Config",
+ description: "Test Description",
+ dataType: ScoreDataType.NUMERIC,
+ minValue: 0,
+ createdAt: new Date("2024-05-11T00:00:00.000Z"),
+ updatedAt: new Date("2024-05-11T00:00:00.000Z"),
+ },
+];
+
+const configThree = [
+ {
+ id: CONFIG_ID_THREE,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ name: "Test Categorical Config",
+ description: "Test Description",
+ dataType: ScoreDataType.CATEGORICAL,
+ categories: [
+ { label: "A", value: 0 },
+ { label: "B", value: 1 },
+ { label: "C", value: 2 },
+ ],
+ createdAt: new Date("2024-05-11T00:00:00.000Z"),
+ updatedAt: new Date("2024-05-11T00:00:00.000Z"),
+ },
+];
+
+describe("/api/public/score-configs API Endpoint", () => {
+ beforeAll(
+ async () => {
+ await pruneDatabase();
+
+ await prisma.scoreConfig.createMany({
+ data: [...configOne, ...configTwo, ...configThree],
+ });
+ },
+ afterAll(async () => {
+ await pruneDatabase();
+ }),
+ );
+
+ it("should GET a score config", async () => {
+ const configId = CONFIG_ID_ONE;
+
+ const getScoreConfig = await makeAPICall<{
+ id: string;
+ }>("GET", `/api/public/score-configs/${configId}`);
+
+ expect(getScoreConfig.status).toBe(200);
+ expect(getScoreConfig.body).toMatchObject({
+ ...configOne[0],
+ isArchived: false,
+ createdAt: "2024-05-10T00:00:00.000Z",
+ updatedAt: "2024-05-10T00:00:00.000Z",
+ });
+ });
+
+ it("test invalid config id input", async () => {
+ const configId = "invalid-config-id";
+
+ const getScoreConfig = await makeAPICall<{
+ message: string;
+ }>("GET", `/api/public/score-configs/${configId}`);
+
+ expect(getScoreConfig.status).toBe(404);
+ expect(getScoreConfig.body).toMatchObject({
+ message: "Score config not found within authorized project",
+ });
+ });
+
+ it("should GET all score configs", async () => {
+ const fetchedConfigs = await makeAPICall<{
+ data: CastedConfig[];
+ meta: object;
+ }>("GET", `/api/public/score-configs?limit=50&page=1`);
+
+ expect(fetchedConfigs.status).toBe(200);
+ expect(fetchedConfigs.body.meta).toMatchObject({
+ page: 1,
+ limit: 50,
+ totalItems: 3,
+ totalPages: 1,
+ });
+
+ expect(fetchedConfigs.body.data.length).toBe(3);
+ expect(fetchedConfigs.body.data[0]).toMatchObject({
+ ...configTwo[0],
+ isArchived: false,
+ createdAt: "2024-05-11T00:00:00.000Z",
+ updatedAt: "2024-05-11T00:00:00.000Z",
+ });
+ });
+
+ it("should return 500 when hitting corrupted score config", async () => {
+ const configId = "corrupted-config-id";
+
+ await prisma.scoreConfig.create({
+ data: {
+ ...configThree[0],
+ id: configId,
+ categories: "invalid-categories",
+ },
+ });
+
+ const getScoreConfig = await makeAPICall<{
+ message: string;
+ }>("GET", `/api/public/score-configs/${configId}`);
+
+ expect(getScoreConfig.status).toBe(500);
+ expect(getScoreConfig.body).toMatchObject({
+ message: "Internal Server Error",
+ });
+ });
+});
diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.ts
index a6f0414c3c..d9fad967c1 100644
--- a/web/src/__tests__/test-utils.ts
+++ b/web/src/__tests__/test-utils.ts
@@ -4,6 +4,7 @@ import { hash } from "bcryptjs";
export const pruneDatabase = async () => {
await prisma.score.deleteMany();
+ await prisma.scoreConfig.deleteMany();
await prisma.observation.deleteMany();
await prisma.trace.deleteMany();
await prisma.datasetItem.deleteMany();
diff --git a/web/src/features/manual-scoring/lib/helpers.ts b/web/src/features/manual-scoring/lib/helpers.ts
index 8d2b96e932..694691ffdd 100644
--- a/web/src/features/manual-scoring/lib/helpers.ts
+++ b/web/src/features/manual-scoring/lib/helpers.ts
@@ -1,4 +1,8 @@
-import { ScoreDataType } from "@langfuse/shared";
+import {
+ type ScoreConfig,
+ ScoreDataType,
+ type CastedConfig,
+} from "@langfuse/shared";
export const isNumericDataType = (dataType: ScoreDataType) =>
dataType === ScoreDataType.NUMERIC;
@@ -13,3 +17,17 @@ export const isPresent = <T>(value: T): value is NonNullable<T> =>
value !== null && value !== undefined && value !== "";
export const isScoreUnsaved = (scoreId?: string): boolean => !scoreId;
+
+export const isCastedConfig = (config: ScoreConfig): config is CastedConfig => {
+ return (
+ config.categories === null ||
+ (Array.isArray(config.categories) &&
+ config.categories.every(
+ (category) =>
+ category !== null &&
+ typeof category === "object" &&
+ "label" in category &&
+ "value" in category,
+ ))
+ );
+};
diff --git a/web/src/pages/api/public/score-configs.ts b/web/src/pages/api/public/score-configs.ts
new file mode 100644
index 0000000000..f7e2d294c8
--- /dev/null
+++ b/web/src/pages/api/public/score-configs.ts
@@ -0,0 +1,109 @@
+import { type CastedConfig, paginationZod } from "@langfuse/shared";
+import { z } from "zod";
+import { prisma } from "@langfuse/shared/src/db";
+import { Prisma } from "@langfuse/shared/src/db";
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+import { isPrismaException } from "@/src/utils/exceptions";
+import { isCastedConfig } from "@/src/features/manual-scoring/lib/helpers";
+
+const ScoreConfigsGetSchema = z.object({
+ ...paginationZod,
+});
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ await runMiddleware(req, res, cors);
+
+ try {
+ // CHECK AUTH
+ const authCheck = await verifyAuthHeaderAndReturnScope(
+ req.headers.authorization,
+ );
+ if (!authCheck.validKey) {
+ return res.status(401).json({
+ message: authCheck.error,
+ });
+ }
+ // END CHECK AUTH
+
+ if (req.method !== "GET") {
+ return res.status(405).json({ message: "Method not allowed" });
+ }
+
+ if (req.method === "GET") {
+ if (authCheck.scope.accessLevel !== "all") {
+ return res.status(401).json({
+ message: "Access denied - need to use basic auth with secret key",
+ });
+ }
+
+ const obj = ScoreConfigsGetSchema.parse(req.query);
+
+ const rawConfigs = await prisma.scoreConfig.findMany({
+ where: {
+ projectId: authCheck.scope.projectId,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ take: obj.limit,
+ skip: (obj.page - 1) * obj.limit,
+ });
+
+ const configs: CastedConfig[] = rawConfigs.filter(isCastedConfig);
+
+ if (configs.length !== rawConfigs.length) {
+ return res.status(500).json({
+ message: "Internal Server Error",
+ error: "Invalid config format encountered",
+ });
+ }
+
+ const totalItemsRes = await prisma.$queryRaw<{ count: bigint }[]>(
+ Prisma.sql`
+ SELECT
+ COUNT(*) as count
+ FROM
+ "score_configs" AS sc
+ WHERE sc.project_id = ${authCheck.scope.projectId}
+ `,
+ );
+
+ const totalItems =
+ totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;
+
+ return res.status(200).json({
+ data: configs,
+ meta: {
+ page: obj.page,
+ limit: obj.limit,
+ totalItems,
+ totalPages: Math.ceil(totalItems / obj.limit),
+ },
+ });
+ }
+ } catch (error: unknown) {
+ console.error(error);
+ if (isPrismaException(error)) {
+ return res.status(500).json({
+ error: "Internal Server Error",
+ });
+ }
+ if (error instanceof z.ZodError) {
+ return res.status(400).json({
+ message: "Invalid request data",
+ error: error.errors,
+ });
+ }
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(500).json({
+ message: "Invalid request data",
+ error: errorMessage,
+ });
+ }
+}
diff --git a/web/src/pages/api/public/score-configs/[configId].ts b/web/src/pages/api/public/score-configs/[configId].ts
new file mode 100644
index 0000000000..4b84a81dd0
--- /dev/null
+++ b/web/src/pages/api/public/score-configs/[configId].ts
@@ -0,0 +1,85 @@
+import { prisma } from "@langfuse/shared/src/db";
+import { type NextApiRequest, type NextApiResponse } from "next";
+import { z } from "zod";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+import { isPrismaException } from "@/src/utils/exceptions";
+import { isCastedConfig } from "@/src/features/manual-scoring/lib/helpers";
+
+const ConfigSchema = z.object({
+ configId: z.string(),
+});
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ await runMiddleware(req, res, cors);
+
+ if (req.method === "GET") {
+ try {
+ // CHECK AUTH
+ const authCheck = await verifyAuthHeaderAndReturnScope(
+ req.headers.authorization,
+ );
+ if (!authCheck.validKey)
+ return res.status(401).json({
+ message: authCheck.error,
+ });
+ // END CHECK AUTH
+
+ const { configId } = ConfigSchema.parse(req.query);
+
+ // CHECK ACCESS SCOPE
+ if (authCheck.scope.accessLevel !== "all") {
+ return res.status(401).json({
+ message: "Access denied - need to use basic auth with secret key",
+ });
+ }
+ // END CHECK ACCESS SCOPE
+
+ const config = await prisma.scoreConfig.findUnique({
+ where: {
+ id: configId,
+ projectId: authCheck.scope.projectId,
+ },
+ });
+
+ if (!config) {
+ return res.status(404).json({
+ message: "Score config not found within authorized project",
+ });
+ }
+
+ if (isCastedConfig(config)) {
+ return res.status(200).json(config);
+ } else {
+ return res.status(500).json({
+ message: "Internal Server Error",
+ error: "Invalid config format encountered",
+ });
+ }
+ } catch (error: unknown) {
+ console.error(error);
+ if (isPrismaException(error)) {
+ return res.status(500).json({
+ error: "Internal Server Error",
+ });
+ }
+ if (error instanceof z.ZodError) {
+ return res.status(400).json({
+ message: "Invalid request data",
+ error: error.errors,
+ });
+ }
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(500).json({
+ message: "Invalid request data",
+ error: errorMessage,
+ });
+ }
+ } else {
+ return res.status(405).json({ message: "Method not allowed" });
+ }
+}