🪢 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(scores-api): allow `source=ANNOTATION` on `POST /api/public/scores` (#13286)
Tobias Wochinger443e7d443a06
diff --git a/fern/apis/client/definition/score.yml b/fern/apis/client/definition/score.ymlindex 4dee0501cc..7f3ab20973 100644--- a/fern/apis/client/definition/score.yml+++ b/fern/apis/client/definition/score.yml@@ -32,6 +32,9 @@ types:configId:type: optional<string>docs: Reference a score config on a score. When set, the score name must equal the config name and scores must comply with the config's range and data type. For categorical scores, the value must map to a config category. Numeric scores might be constrained by the score config's max and min values+ source:+ type: optional<CreateScoreSource>+ docs: The source of the score. Defaults to API. Set to ANNOTATION to prefill scores (e.g. from an LLM) for a human reviewer to verify in an annotation queue. When source is ANNOTATION, a configId is required unless dataType is CORRECTION. EVAL is reserved for internal evaluator outputs and is not accepted on this endpoint.examples:- value:name: "novelty"@@ -77,6 +80,22 @@ types:name: "hallucination"value: 0datasetRunId: "7891-5678-90ab-hijk"+ - value:+ name: "accuracy"+ value: 0.9+ dataType: "NUMERIC"+ configId: "9203-4567-89ab-cdef"+ traceId: "cdef-1234-5678-90ab"+ source: "ANNOTATION"++ CreateScoreSource:+ docs: |+ Source values accepted when creating a score via the public API.+ EVAL is reserved for internal evaluator outputs and is intentionally not+ exposed here.+ enum:+ - API+ - ANNOTATIONScoreDataType:enum:diff --git a/fern/apis/server/definition/legacy/score-v1.yml b/fern/apis/server/definition/legacy/score-v1.ymlindex 5cc5a18ac4..1154735814 100644--- a/fern/apis/server/definition/legacy/score-v1.yml+++ b/fern/apis/server/definition/legacy/score-v1.yml@@ -46,6 +46,9 @@ types:configId:type: optional<string>docs: Reference a score config on a score. The unique langfuse identifier of a score config. When passing this field, the dataType and stringValue fields are automatically populated.+ source:+ type: optional<CreateScoreSource>+ docs: The source of the score. Defaults to API. Set to ANNOTATION to prefill scores (e.g. from an LLM) for a human reviewer to verify in an annotation queue. When source is ANNOTATION, a configId is required unless dataType is CORRECTION. EVAL is reserved for internal evaluator outputs and is not accepted on this endpoint.examples:- value:name: "novelty"@@ -90,6 +93,22 @@ types:value: "Great explanation of the concept"dataType: "TEXT"traceId: "cdef-1234-5678-90ab"+ - value:+ name: "accuracy"+ value: 0.9+ dataType: "NUMERIC"+ configId: "9203-4567-89ab-cdef"+ traceId: "cdef-1234-5678-90ab"+ source: "ANNOTATION"+ queueId: "aq-1234-5678-90ab-cdef"+ CreateScoreSource:+ docs: |+ Source values accepted when creating a score via the public REST API.+ EVAL is reserved for internal evaluator outputs and is intentionally not+ exposed here — use commons.ScoreSource when reading scores.+ enum:+ - API+ - ANNOTATIONCreateScoreResponse:properties:id:diff --git a/packages/shared/src/domain/scores.ts b/packages/shared/src/domain/scores.tsindex da5f7ffea8..ef395ab9a2 100644--- a/packages/shared/src/domain/scores.ts+++ b/packages/shared/src/domain/scores.ts@@ -10,6 +10,35 @@ export const ScoreSourceEnum = {export const ScoreSourceDomain = z.enum(ScoreSourceArray);export type ScoreSourceType = z.infer<typeof ScoreSourceDomain>;+/**+ * Source values external callers may set on the public create-score endpoint.+ * EVAL is reserved for internal evaluator outputs. The `satisfies` clause+ * keeps this a provable subset of {@link ScoreSourceArray} at compile time.+ */+export const PublicApiCreateScoreSourceDomain = z.enum([+ ScoreSourceEnum.API,+ ScoreSourceEnum.ANNOTATION,+] as const satisfies readonly ScoreSourceType[]);++/**+ * Annotation scores need a matching score config so they can render in the+ * annotation queue UI. CORRECTION scores are the one exception — by design+ * they never carry a configId. This predicate + message are shared by the+ * zod refine on {@link PostScoresBody} (sync 400 on REST) and the check in+ * `validateAndInflateScore` (async drop for ingestion/SDK callers).+ */+export const ANNOTATION_SCORE_REQUIRES_CONFIG_ID_MESSAGE =+ "configId is required when source is ANNOTATION (except for CORRECTION scores).";++export const isAnnotationScoreMissingConfigId = (body: {+ source?: ScoreSourceType | null;+ configId?: string | null;+ dataType?: ScoreDataTypeType;+}): boolean =>+ body.source === ScoreSourceEnum.ANNOTATION &&+ !body.configId &&+ body.dataType !== ScoreDataTypeEnum.CORRECTION;+export const CORRECTION_NAME = "output" as const;export const TEXT_SCORE_MAX_LENGTH = 500 as const;diff --git a/packages/shared/src/features/scores/interfaces/api/shared.ts b/packages/shared/src/features/scores/interfaces/api/shared.tsindex 5aecdc9060..fc243d5e26 100644--- a/packages/shared/src/features/scores/interfaces/api/shared.ts+++ b/packages/shared/src/features/scores/interfaces/api/shared.ts@@ -4,8 +4,12 @@ import { stringDateTime } from "../../../../utils/typeChecks";import { applyScoreValidation } from "../../../../utils/scores";import { PostScoreBodyFoundationSchema } from "../shared";import {+ ANNOTATION_SCORE_REQUIRES_CONFIG_ID_MESSAGE,+ isAnnotationScoreMissingConfigId,+ PublicApiCreateScoreSourceDomain,ScoreDataTypeDomain,ScoreSourceDomain,+ ScoreSourceEnum,TEXT_SCORE_MAX_LENGTH,} from "../../../../domain/scores";import { singleFilter } from "../../../../interfaces/filters";@@ -75,11 +79,12 @@ export const GetScoresQuery = z.object({});// POST /scores-/**- * PostScoresBody is copied for the ingestion API as `ScoreBody`. Please copy any changes here in `packages/shared/src/features/ingestion/types.ts`- */+// Roughly mirrors ScoreBody in `packages/shared/src/server/ingestion/types.ts`;+// keep them in sync for fields that cross both surfaces.export const PostScoresBody = applyScoreValidation(- PostScoreBodyFoundationSchema.and(+ PostScoreBodyFoundationSchema.extend({+ source: PublicApiCreateScoreSourceDomain.default(ScoreSourceEnum.API),+ }).and(z.discriminatedUnion("dataType", [z.object({value: z.number(),@@ -116,7 +121,10 @@ export const PostScoresBody = applyScoreValidation(}),]),),-);+).refine((data) => !isAnnotationScoreMissingConfigId(data), {+ message: ANNOTATION_SCORE_REQUIRES_CONFIG_ID_MESSAGE,+ path: ["configId"],+});export const PostScoresResponse = z.object({ id: z.string() });diff --git a/packages/shared/src/server/ingestion/validateAndInflateScore.ts b/packages/shared/src/server/ingestion/validateAndInflateScore.tsindex 9398403fbc..43c17aa336 100644--- a/packages/shared/src/server/ingestion/validateAndInflateScore.ts+++ b/packages/shared/src/server/ingestion/validateAndInflateScore.ts@@ -1,4 +1,6 @@import {+ ANNOTATION_SCORE_REQUIRES_CONFIG_ID_MESSAGE,+ isAnnotationScoreMissingConfigId,ScoreBodyWithoutConfig,ScoreConfigDomain,type ScoreDataTypeType,@@ -23,6 +25,13 @@ export async function validateAndInflateScore() {const { body, projectId, scoreId } = params;+ // Central choke point: both POST /api/public/scores and+ // POST /api/public/ingestion enqueue events that run through this function+ // in the worker, so enforcing here covers both entry points.+ if (isAnnotationScoreMissingConfigId(body)) {+ throw new InvalidRequestError(ANNOTATION_SCORE_REQUIRES_CONFIG_ID_MESSAGE);+ }+if (body.configId) {const config = await prisma.scoreConfig.findFirst({where: {diff --git a/web/public/generated/api-client/openapi.yml b/web/public/generated/api-client/openapi.ymlindex 73df3f3bab..ba9c4c873c 100644--- a/web/public/generated/api-client/openapi.yml+++ b/web/public/generated/api-client/openapi.yml@@ -98,9 +98,28 @@ components:and data type. For categorical scores, the value must map to aconfig category. Numeric scores might be constrained by the scoreconfig's max and min values+ source:+ $ref: '#/components/schemas/CreateScoreSource'+ nullable: true+ description: >-+ The source of the score. Defaults to API. Set to ANNOTATION to+ prefill scores (e.g. from an LLM) for a human reviewer to verify in+ an annotation queue. When source is ANNOTATION, a configId is+ required unless dataType is CORRECTION. EVAL is reserved for+ internal evaluator outputs and is not accepted on this endpoint.required:- name- value+ CreateScoreSource:+ title: CreateScoreSource+ type: string+ enum:+ - API+ - ANNOTATION+ description: |-+ Source values accepted when creating a score via the public API.+ EVAL is reserved for internal evaluator outputs and is intentionally not+ exposed here.ScoreDataType:title: ScoreDataTypetype: stringdiff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex e12fae2408..5c9941984d 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -10231,9 +10231,28 @@ components:Reference a score config on a score. The unique langfuse identifierof a score config. When passing this field, the dataType andstringValue fields are automatically populated.+ source:+ $ref: '#/components/schemas/legacyCreateScoreSource'+ nullable: true+ description: >-+ The source of the score. Defaults to API. Set to ANNOTATION to+ prefill scores (e.g. from an LLM) for a human reviewer to verify in+ an annotation queue. When source is ANNOTATION, a configId is+ required unless dataType is CORRECTION. EVAL is reserved for+ internal evaluator outputs and is not accepted on this endpoint.required:- name- value+ legacyCreateScoreSource:+ title: legacyCreateScoreSource+ type: string+ enum:+ - API+ - ANNOTATION+ description: |-+ Source values accepted when creating a score via the public REST API.+ EVAL is reserved for internal evaluator outputs and is intentionally not+ exposed here — use commons.ScoreSource when reading scores.legacyCreateScoreResponse:title: legacyCreateScoreResponsetype: objectdiff --git a/web/src/__tests__/server/scores-api-v1.servertest.ts b/web/src/__tests__/server/scores-api-v1.servertest.tsindex 6621468b3f..8d686b9622 100644--- a/web/src/__tests__/server/scores-api-v1.servertest.ts+++ b/web/src/__tests__/server/scores-api-v1.servertest.ts@@ -1422,4 +1422,158 @@ describe("/api/public/scores API Endpoint", () => {expect(sessionsRes.status).toBe(403);});});++ describe("POST /api/public/scores source field", () => {+ it("defaults source to API when omitted", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ const traceId = v4();+ await createTracesCh([+ createTrace({ id: traceId, project_id: projectId }),+ ]);++ const scoreId = v4();+ const response = await makeAPICall(+ "POST",+ "/api/public/scores",+ { id: scoreId, traceId, name: "feedback", value: 1 },+ auth,+ );++ expect(response.status).toBe(200);++ await waitForExpect(async () => {+ const score = await getScoreById({ projectId, scoreId });+ expect(score).toBeDefined();+ expect(score!.source).toBe("API");+ });+ }, 15000);++ it("rejects source=EVAL (reserved for internal evaluator outputs)", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ const traceId = v4();+ await createTracesCh([+ createTrace({ id: traceId, project_id: projectId }),+ ]);++ const response = await makeAPICall(+ "POST",+ "/api/public/scores",+ {+ id: v4(),+ traceId,+ name: "llm-judge",+ value: 0.8,+ source: "EVAL",+ },+ auth,+ );++ expect(response.status).toBe(400);+ });++ it("accepts source=ANNOTATION with a matching configId", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ const configId = v4();+ await prisma.scoreConfig.create({+ data: {+ id: configId,+ name: "helpfulness",+ dataType: "NUMERIC",+ maxValue: 1,+ projectId,+ },+ });++ const traceId = v4();+ await createTracesCh([+ createTrace({ id: traceId, project_id: projectId }),+ ]);++ const scoreId = v4();+ const response = await makeAPICall(+ "POST",+ "/api/public/scores",+ {+ id: scoreId,+ traceId,+ name: "helpfulness",+ value: 0.9,+ dataType: "NUMERIC",+ configId,+ source: "ANNOTATION",+ },+ auth,+ );++ expect(response.status).toBe(200);++ await waitForExpect(async () => {+ const score = await getScoreById({ projectId, scoreId });+ expect(score).toBeDefined();+ expect(score!.source).toBe("ANNOTATION");+ expect(score!.configId).toBe(configId);+ expect(score!.authorUserId).toBeNull();+ });+ }, 15000);++ it("rejects source=ANNOTATION without a configId", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ const traceId = v4();+ await createTracesCh([+ createTrace({ id: traceId, project_id: projectId }),+ ]);++ const response = await makeAPICall(+ "POST",+ "/api/public/scores",+ {+ id: v4(),+ traceId,+ name: "helpfulness",+ value: 0.9,+ dataType: "NUMERIC",+ source: "ANNOTATION",+ },+ auth,+ );++ expect(response.status).toBe(400);+ });++ it("accepts source=ANNOTATION for CORRECTION scores without a configId", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ const traceId = v4();+ await createTracesCh([+ createTrace({ id: traceId, project_id: projectId }),+ ]);++ const scoreId = v4();+ const response = await makeAPICall(+ "POST",+ "/api/public/scores",+ {+ id: scoreId,+ traceId,+ name: "output",+ value: "The corrected output",+ dataType: "CORRECTION",+ source: "ANNOTATION",+ },+ auth,+ );++ expect(response.status).toBe(200);++ await waitForExpect(+ async () => {+ const score = await getScoreById({ projectId, scoreId });+ expect(score).toBeDefined();+ expect(score!.source).toBe("ANNOTATION");+ expect(score!.dataType).toBe("CORRECTION");+ },+ 10000,+ 500,+ );+ }, 15000);+ });});diff --git a/web/src/__tests__/server/validateAndInflateScore.servertest.ts b/web/src/__tests__/server/validateAndInflateScore.servertest.tsnew file mode 100644index 0000000000..f5e371fc0d--- /dev/null+++ b/web/src/__tests__/server/validateAndInflateScore.servertest.ts@@ -0,0 +1,143 @@+/** @jest-environment node */+import { v4 } from "uuid";+import { prisma } from "@langfuse/shared/src/db";+import {+ createOrgProjectAndApiKey,+ validateAndInflateScore,+} from "@langfuse/shared/src/server";+import {+ InvalidRequestError,+ LangfuseNotFoundError,+ ScoreSourceEnum,+} from "@langfuse/shared";++describe("validateAndInflateScore", () => {+ describe("configId scoping", () => {+ it("throws LangfuseNotFoundError when configId belongs to another project", async () => {+ // Config owned by a different project than the caller.+ const { projectId: ownerProjectId } = await createOrgProjectAndApiKey();+ const { projectId: callerProjectId } = await createOrgProjectAndApiKey();+ const foreignConfigId = v4();+ await prisma.scoreConfig.create({+ data: {+ id: foreignConfigId,+ name: "helpfulness",+ dataType: "NUMERIC",+ maxValue: 1,+ projectId: ownerProjectId,+ },+ });++ await expect(+ validateAndInflateScore({+ projectId: callerProjectId,+ scoreId: v4(),+ body: {+ id: v4(),+ name: "helpfulness",+ traceId: v4(),+ value: 0.5,+ dataType: "NUMERIC",+ configId: foreignConfigId,+ source: ScoreSourceEnum.ANNOTATION,+ environment: "default",+ },+ }),+ ).rejects.toThrow(LangfuseNotFoundError);+ });++ it("throws LangfuseNotFoundError when configId does not exist at all", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ await expect(+ validateAndInflateScore({+ projectId,+ scoreId: v4(),+ body: {+ id: v4(),+ name: "helpfulness",+ traceId: v4(),+ value: 0.5,+ dataType: "NUMERIC",+ configId: v4(),+ source: ScoreSourceEnum.ANNOTATION,+ environment: "default",+ },+ }),+ ).rejects.toThrow(LangfuseNotFoundError);+ });++ it("accepts a configId owned by the caller's project", async () => {+ const { projectId } = await createOrgProjectAndApiKey();+ const configId = v4();+ await prisma.scoreConfig.create({+ data: {+ id: configId,+ name: "helpfulness",+ dataType: "NUMERIC",+ maxValue: 1,+ projectId,+ },+ });++ await expect(+ validateAndInflateScore({+ projectId,+ scoreId: v4(),+ body: {+ id: v4(),+ name: "helpfulness",+ traceId: v4(),+ value: 0.5,+ dataType: "NUMERIC",+ configId,+ source: ScoreSourceEnum.ANNOTATION,+ environment: "default",+ },+ }),+ ).resolves.toBeDefined();+ });+ });++ describe("source=ANNOTATION rule", () => {+ it("throws InvalidRequestError when source is ANNOTATION without a configId", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ await expect(+ validateAndInflateScore({+ projectId,+ scoreId: v4(),+ body: {+ id: v4(),+ name: "helpfulness",+ traceId: v4(),+ value: 0.5,+ dataType: "NUMERIC",+ source: ScoreSourceEnum.ANNOTATION,+ environment: "default",+ },+ }),+ ).rejects.toThrow(InvalidRequestError);+ });++ it("allows source=ANNOTATION without a configId for CORRECTION scores", async () => {+ const { projectId } = await createOrgProjectAndApiKey();++ await expect(+ validateAndInflateScore({+ projectId,+ scoreId: v4(),+ body: {+ id: v4(),+ name: "output",+ traceId: v4(),+ value: "corrected output text",+ dataType: "CORRECTION",+ source: ScoreSourceEnum.ANNOTATION,+ environment: "default",+ },+ }),+ ).resolves.toBeDefined();+ });+ });+});