Skip to content

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

feat(evals): allow deleting evaluators (UI, API, MCP) (#14228)

Tobias Wochinger5ed4f2935017
diff --git a/fern/apis/server/definition/unstable/evaluators.yml b/fern/apis/server/definition/unstable/evaluators.yml
index 0085a4dbca..e3c2597098 100644
--- a/fern/apis/server/definition/unstable/evaluators.yml
+++ b/fern/apis/server/definition/unstable/evaluators.yml
@@ -293,7 +293,40 @@ service:
- errors.TooManyRequestsError
- errors.InternalServerError
+ delete:
+ docs: |
+ Delete an evaluator.
+
+ Important behavior:
+ - This deletes the evaluator including all of its stored versions; `evaluatorId` may reference any version.
+ - The API returns `409` while evaluation rules still reference the evaluator. Delete those evaluation rules first.
+ - Langfuse-managed evaluators (`scope=managed`) cannot be deleted; the API returns `403`.
+ - Scores already produced by the evaluator are not deleted.
+ method: DELETE
+ path: /evaluators/{evaluatorId}
+ path-parameters:
+ evaluatorId:
+ type: string
+ docs: Evaluator identifier returned by the evaluator endpoints.
+ response: DeleteEvaluatorResponse
+ errors:
+ - errors.BadRequestError
+ - errors.UnauthorizedError
+ - errors.AccessDeniedError
+ - errors.NotFoundError
+ - errors.MethodNotAllowedError
+ - errors.ConflictError
+ - errors.TooManyRequestsError
+ - errors.InternalServerError
+
types:
+ DeleteEvaluatorResponse:
+ docs: Confirmation response returned after successful deletion.
+ properties:
+ message:
+ type: string
+ docs: Always `Evaluator successfully deleted`.
+
Evaluator:
docs: |
One evaluator that can be used for scoring.
diff --git a/packages/shared/prisma/migrations/20260612000000_drop_job_executions_job_template_id_fkey/migration.sql b/packages/shared/prisma/migrations/20260612000000_drop_job_executions_job_template_id_fkey/migration.sql
new file mode 100644
index 0000000000..b20511b490
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260612000000_drop_job_executions_job_template_id_fkey/migration.sql
@@ -0,0 +1,2 @@
+-- DropForeignKey
+ALTER TABLE "job_executions" DROP CONSTRAINT IF EXISTS "job_executions_job_template_id_fkey";
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 2385231e96..fb6b88e804 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -1007,7 +1007,6 @@ model EvalTemplate {
sourceCode String? @map("source_code") @db.VarChar(262144)
sourceCodeLanguage EvalTemplateSourceCodeLanguage? @map("source_code_language")
JobConfiguration JobConfiguration[]
- JobExecution JobExecution[]
@@unique([projectId, name, version])
@@index([projectId, id])
@@ -1093,7 +1092,6 @@ model JobExecution {
jobConfiguration JobConfiguration @relation(fields: [jobConfigurationId], references: [id], onDelete: Cascade)
jobTemplateId String? @map("job_template_id")
- jobTemplate EvalTemplate? @relation(fields: [jobTemplateId], references: [id], onDelete: SetNull, onUpdate: NoAction)
status JobExecutionStatus
startTime DateTime? @map("start_time")
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 1a69277474..99b11be755 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -7525,6 +7525,85 @@ paths:
$ref: '#/components/schemas/unstablePublicApiError'
security:
- BasicAuth: []
+ delete:
+ description: >-
+ Delete an evaluator.
+
+
+ Important behavior:
+
+ - This deletes the evaluator including all of its stored versions;
+ `evaluatorId` may reference any version.
+
+ - The API returns `409` while evaluation rules still reference the
+ evaluator. Delete those evaluation rules first.
+
+ - Langfuse-managed evaluators (`scope=managed`) cannot be deleted; the
+ API returns `403`.
+
+ - Scores already produced by the evaluator are not deleted.
+ operationId: unstable_evaluators_delete
+ tags:
+ - UnstableEvaluators
+ parameters:
+ - name: evaluatorId
+ in: path
+ description: Evaluator identifier returned by the evaluator endpoints.
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/unstableDeleteEvaluatorResponse'
+ '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: {}
+ '409':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/unstablePublicApiError'
+ '429':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/unstablePublicApiError'
+ '500':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/unstablePublicApiError'
+ security:
+ - BasicAuth: []
components:
schemas:
AnnotationQueueStatus:
@@ -14425,6 +14504,16 @@ components:
- name
- scope
- type
+ unstableDeleteEvaluatorResponse:
+ title: unstableDeleteEvaluatorResponse
+ type: object
+ description: Confirmation response returned after successful deletion.
+ properties:
+ message:
+ type: string
+ description: Always `Evaluator successfully deleted`.
+ required:
+ - message
unstableEvaluator:
title: unstableEvaluator
oneOf:
diff --git a/web/src/__tests__/server/evals-trpc.servertest.ts b/web/src/__tests__/server/evals-trpc.servertest.ts
index 2751d0c0ca..468fb9463b 100644
--- a/web/src/__tests__/server/evals-trpc.servertest.ts
+++ b/web/src/__tests__/server/evals-trpc.servertest.ts
@@ -1113,173 +1113,257 @@ describe("evals trpc", () => {
});
});
- // TODO: moved to LFE-4573
- // describe("evals.deleteEvalTemplate", () => {
- // it("should successfully delete an eval template", async () => {
- // const { project, caller } = await prepare();
-
- // // Create a template to delete
- // const evalTemplate = await prisma.evalTemplate.create({
- // data: {
- // projectId: project.id,
- // name: "test-template",
- // version: 1,
- // prompt: "test prompt",
- // model: "test-model",
- // modelParams: {},
- // vars: [],
- // outputDefinition: {
- // score: "test-score",
- // reasoning: "test-reasoning",
- // },
- // provider: "test-provider",
- // },
- // });
-
- // // Delete the template
- // await caller.evals.deleteEvalTemplate({
- // projectId: project.id,
- // evalTemplateId: evalTemplate.id,
- // });
-
- // // Verify template is deleted
- // const deletedTemplate = await prisma.evalTemplate.findUnique({
- // where: {
- // id: evalTemplate.id,
- // },
- // });
- // expect(deletedTemplate).toBeNull();
- // });
-
- // it("should set evalTemplateId to null for associated eval jobs when template is deleted", async () => {
- // const { project, caller } = await prepare();
-
- // // Create a template
- // const evalTemplate = await prisma.evalTemplate.create({
- // data: {
- // projectId: project.id,
- // name: "test-template",
- // version: 1,
- // prompt: "test prompt",
- // model: "test-model",
- // modelParams: {},
- // vars: [],
- // outputDefinition: {
- // score: "test-score",
- // reasoning: "test-reasoning",
- // },
- // provider: "test-provider",
- // },
- // });
-
- // // Create an eval job linked to this template
- // const evalJob = await prisma.jobConfiguration.create({
- // data: {
- // projectId: project.id,
- // jobType: "EVAL",
- // scoreName: "test-score",
- // filter: [],
- // targetObject: EvalTargetObject.TRACE,
- // variableMapping: [],
- // sampling: 1,
- // delay: 0,
- // status: "ACTIVE",
- // timeScope: ["NEW"],
- // evalTemplateId: evalTemplate.id,
- // },
- // });
-
- // // Delete the template
- // await caller.evals.deleteEvalTemplate({
- // projectId: project.id,
- // evalTemplateId: evalTemplate.id,
- // });
-
- // // Verify template is deleted
- // const deletedTemplate = await prisma.evalTemplate.findUnique({
- // where: {
- // id: evalTemplate.id,
- // },
- // });
- // expect(deletedTemplate).toBeNull();
-
- // // Verify eval job still exists but has evalTemplateId set to null
- // const updatedJob = await prisma.jobConfiguration.findUnique({
- // where: {
- // id: evalJob.id,
- // },
- // });
- // expect(updatedJob).not.toBeNull();
- // expect(updatedJob?.evalTemplateId).toBeNull();
- // });
-
- // it("should throw error when trying to delete non-existent eval template", async () => {
- // const { project, caller } = await prepare();
-
- // await expect(
- // caller.evals.deleteEvalTemplate({
- // projectId: project.id,
- // evalTemplateId: "non-existent-id",
- // }),
- // ).rejects.toThrow("Template not found");
- // });
-
- // it("should throw error when user lacks evalTemplate:CUD access scope", async () => {
- // const { project, session } = await prepare();
-
- // // Create a session with limited permissions
- // const limitedSession: Session = {
- // ...session,
- // user: {
- // id: session.user!.id,
- // name: session.user!.name,
- // canCreateOrganizations: session.user!.canCreateOrganizations,
- // admin: false,
- // featureFlags: session.user!.featureFlags,
- // organizations: [
- // {
- // ...session.user!.organizations[0],
- // role: "MEMBER",
- // projects: [
- // {
- // ...session.user!.organizations[0].projects[0],
- // role: "VIEWER", // VIEWER role doesn't have evalTemplate:CUD scope
- // },
- // ],
- // },
- // ],
- // },
- // expires: session.expires,
- // environment: session.environment,
- // };
- // const limitedCtx = createInnerTRPCContext({ session: limitedSession });
- // const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });
-
- // // Create a template
- // const evalTemplate = await prisma.evalTemplate.create({
- // data: {
- // projectId: project.id,
- // name: "test-template",
- // version: 1,
- // prompt: "test prompt",
- // model: "test-model",
- // modelParams: {},
- // vars: [],
- // outputDefinition: {
- // score: "test-score",
- // reasoning: "test-reasoning",
- // },
- // provider: "test-provider",
- // },
- // });
-
- // // Attempt to delete with limited permissions
- // await expect(
- // limitedCaller.evals.deleteEvalTemplate({
- // projectId: project.id,
- // evalTemplateId: evalTemplate.id,
- // }),
- // ).rejects.toThrow("User does not have access to this resource or action");
- // });
- // });
+ const createTemplateVersion = (
+ projectId: string | null,
+ name: string,
+ version: number,
+ ) =>
+ prisma.evalTemplate.create({
+ data: {
+ projectId,
+ name,
+ version,
+ prompt: "test prompt",
+ outputDefinition: createNumericEvalOutputDefinition({
+ reasoningDescription: "Why",
+ scoreDescription: "How good",
+ }),
+ },
+ });
+
+ describe("evals.evalTemplateUsage", () => {
+ it("should return running evaluators referencing any version of the family", async () => {
+ const { project, caller } = await prepare();
+
+ const v1 = await createTemplateVersion(project.id, "usage-template", 1);
+ const v2 = await createTemplateVersion(project.id, "usage-template", 2);
+
+ const config = await prisma.jobConfiguration.create({
+ data: {
+ projectId: project.id,
+ jobType: "EVAL",
+ evalTemplateId: v1.id,
+ scoreName: "usage-score",
+ filter: [],
+ targetObject: EvalTargetObject.TRACE,
+ variableMapping: [],
+ sampling: 1,
+ delay: 0,
+ status: "ACTIVE",
+ timeScope: ["NEW"],
+ },
+ });
+
+ // queried via the latest version while the config references the old one
+ const usage = await caller.evals.evalTemplateUsage({
+ projectId: project.id,
+ evalTemplateId: v2.id,
+ });
+
+ expect(usage).toEqual([{ id: config.id, scoreName: "usage-score" }]);
+ });
+
+ it("should return an empty list for unused evaluators", async () => {
+ const { project, caller } = await prepare();
+
+ const template = await createTemplateVersion(
+ project.id,
+ "unused-template",
+ 1,
+ );
+
+ const usage = await caller.evals.evalTemplateUsage({
+ projectId: project.id,
+ evalTemplateId: template.id,
+ });
+
+ expect(usage).toEqual([]);
+ });
+
+ it("should not expose evaluators of another project", async () => {
+ const { project, caller } = await prepare();
+ const { project: otherProject } = await prepare();
+
+ const otherProjectTemplate = await createTemplateVersion(
+ otherProject.id,
+ "other-project-usage-template",
+ 1,
+ );
+
+ await expect(
+ caller.evals.evalTemplateUsage({
+ projectId: project.id,
+ evalTemplateId: otherProjectTemplate.id,
+ }),
+ ).rejects.toThrow("Evaluator not found");
+ });
+ });
+
+ describe("evals.deleteEvalTemplate", () => {
+ it("should delete all versions of a project-owned evaluator", async () => {
+ const { project, caller } = await prepare();
+
+ const v1 = await createTemplateVersion(project.id, "delete-template", 1);
+ const v2 = await createTemplateVersion(project.id, "delete-template", 2);
+
+ await caller.evals.deleteEvalTemplate({
+ projectId: project.id,
+ evalTemplateId: v1.id,
+ });
+
+ const remainingVersions = await prisma.evalTemplate.findMany({
+ where: { id: { in: [v1.id, v2.id] } },
+ });
+ expect(remainingVersions).toHaveLength(0);
+
+ const auditLogs = await prisma.auditLog.findMany({
+ where: {
+ projectId: project.id,
+ resourceType: "evalTemplate",
+ action: "delete",
+ resourceId: { in: [v1.id, v2.id] },
+ },
+ });
+ expect(auditLogs).toHaveLength(2);
+ });
+
+ it("should block deletion while a running evaluator references any version", async () => {
+ const { project, caller } = await prepare();
+
+ const v1 = await createTemplateVersion(project.id, "in-use-template", 1);
+ const v2 = await createTemplateVersion(project.id, "in-use-template", 2);
+
+ // job config references the old version; deleting via the latest
+ // version id must still be blocked
+ await prisma.jobConfiguration.create({
+ data: {
+ projectId: project.id,
+ jobType: "EVAL",
+ evalTemplateId: v1.id,
+ scoreName: "in-use-score",
+ filter: [],
+ targetObject: EvalTargetObject.TRACE,
+ variableMapping: [],
+ sampling: 1,
+ delay: 0,
+ status: "INACTIVE",
+ timeScope: ["NEW"],
+ },
+ });
+
+ await expect(
+ caller.evals.deleteEvalTemplate({
+ projectId: project.id,
+ evalTemplateId: v2.id,
+ }),
+ ).rejects.toThrow(
+ 'Evaluator "in-use-template" is in use by 1 running evaluator(s): "in-use-score". Delete those running evaluators first.',
+ );
+
+ const remainingVersions = await prisma.evalTemplate.findMany({
+ where: { id: { in: [v1.id, v2.id] } },
+ });
+ expect(remainingVersions).toHaveLength(2);
+ });
+
+ it("should reject deletion of langfuse-managed evaluators", async () => {
+ const { project, caller } = await prepare();
+
+ const managedTemplate = await createTemplateVersion(
+ null,
+ `langfuse-managed-template-${project.id}`,
+ 1,
+ );
+
+ try {
+ await expect(
+ caller.evals.deleteEvalTemplate({
+ projectId: project.id,
+ evalTemplateId: managedTemplate.id,
+ }),
+ ).rejects.toThrow("Langfuse-managed evaluators cannot be deleted");
+ } finally {
+ // managed templates are global and not covered by the org cleanup
+ await prisma.evalTemplate.delete({ where: { id: managedTemplate.id } });
+ }
+ });
+
+ it("should not delete evaluators of another project", async () => {
+ const { project, caller } = await prepare();
+ const { project: otherProject } = await prepare();
+
+ const otherProjectTemplate = await createTemplateVersion(
+ otherProject.id,
+ "other-project-template",
+ 1,
+ );
+
+ await expect(
+ caller.evals.deleteEvalTemplate({
+ projectId: project.id,
+ evalTemplateId: otherProjectTemplate.id,
+ }),
+ ).rejects.toThrow("Evaluator not found");
+
+ const untouchedTemplate = await prisma.evalTemplate.findUnique({
+ where: { id: otherProjectTemplate.id },
+ });
+ expect(untouchedTemplate).not.toBeNull();
+ });
+
+ it("should throw error when trying to delete non-existent eval template", async () => {
+ const { project, caller } = await prepare();
+
+ await expect(
+ caller.evals.deleteEvalTemplate({
+ projectId: project.id,
+ evalTemplateId: "non-existent-id",
+ }),
+ ).rejects.toThrow("Evaluator not found");
+ });
+
+ it("should throw error when user lacks evalTemplate:CUD access scope", async () => {
+ const { project, session } = await prepare();
+
+ const limitedSession: Session = {
+ ...session,
+ user: {
+ id: session.user!.id,
+ name: session.user!.name,
+ canCreateOrganizations: session.user!.canCreateOrganizations,
+ admin: false,
+ featureFlags: session.user!.featureFlags,
+ organizations: [
+ {
+ ...session.user!.organizations[0],
+ role: "MEMBER",
+ projects: [
+ {
+ ...session.user!.organizations[0].projects[0],
+ role: "VIEWER", // VIEWER role doesn't have evalTemplate:CUD scope
+ },
+ ],
+ },
+ ],
+ },
+ expires: session.expires,
+ environment: session.environment,
+ };
+ const limitedCtx = createInnerTRPCContext({ session: limitedSession });
+ const limitedCaller = appRouter.createCaller({ ...limitedCtx, prisma });
+
+ const evalTemplate = await createTemplateVersion(
+ project.id,
+ "no-access-template",
+ 1,
+ );
+
+ await expect(
+ limitedCaller.evals.deleteEvalTemplate({
+ projectId: project.id,
+ evalTemplateId: evalTemplate.id,
+ }),
+ ).rejects.toThrow("User does not have access to this resource or action");
+ });
+ });
});
diff --git a/web/src/__tests__/server/evaluator-repository.servertest.ts b/web/src/__tests__/server/evaluator-repository.servertest.ts
new file mode 100644
index 0000000000..e6b88037c8
--- /dev/null
+++ b/web/src/__tests__/server/evaluator-repository.servertest.ts
@@ -0,0 +1,298 @@
+import { EvalTemplateType } from "@prisma/client";
+import { prisma } from "@langfuse/shared/src/db";
+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import {
+ deleteEvalTemplatesByIds,
+ findDefaultModelEvalTemplateIds,
+ findEvalTemplateById,
+ findEvalTemplateFamilyVersions,
+ findJobConfigurationsReferencingEvalTemplates,
+ lockEvalTemplateFamilyVersions,
+} from "@/src/features/evals/server/evaluatorRepository";
+
+const __orgIds: string[] = [];
+const __managedTemplateIds: string[] = [];
+
+const prepareProject = async () => {
+ const { project, org } = await createOrgProjectAndApiKey();
+ __orgIds.push(org.id);
+ return project;
+};
+
+const createTemplate = async (data: {
+ projectId: string | null;
+ name: string;
+ version?: number;
+ type?: EvalTemplateType;
+ provider?: string | null;
+ model?: string | null;
+}) => {
+ const template = await prisma.evalTemplate.create({
+ data: {
+ projectId: data.projectId,
+ name: data.name,
+ version: data.version ?? 1,
+ type: data.type ?? EvalTemplateType.LLM_AS_JUDGE,
+ provider: data.provider ?? null,
+ model: data.model ?? null,
+ prompt: "test prompt",
+ },
+ });
+
+ // managed templates are global and not covered by the org cleanup
+ if (!data.projectId) __managedTemplateIds.push(template.id);
+
+ return template;
+};
+
+const createJobConfiguration = (params: {
+ projectId: string;
+ evalTemplateId: string;
+ scoreName: string;
+}) =>
+ prisma.jobConfiguration.create({
+ data: {
+ projectId: params.projectId,
+ jobType: "EVAL",
+ evalTemplateId: params.evalTemplateId,
+ scoreName: params.scoreName,
+ filter: [],
+ targetObject: "trace",
+ variableMapping: [],
+ sampling: 1,
+ delay: 0,
+ status: "INACTIVE",
+ timeScope: ["NEW"],
+ },
+ });
+
+describe("evaluatorRepository", () => {
+ afterAll(async () => {
+ await prisma.evalTemplate.deleteMany({
+ where: { id: { in: __managedTemplateIds } },
+ });
+ await prisma.organization.deleteMany({
+ where: { id: { in: __orgIds } },
+ });
+ });
+
+ describe("findDefaultModelEvalTemplateIds", () => {
+ it("only returns LLM-as-judge templates that depend on the default model", async () => {
+ const project = await prepareProject();
+ const dependentTemplate = await createTemplate({
+ projectId: project.id,
+ name: "default-model-dependent",
+ });
+ const templateWithOwnModel = await createTemplate({
+ projectId: project.id,
+ name: "own-model",
+ provider: "openai",
+ model: "gpt-4.1",
+ });
+ const codeTemplate = await createTemplate({
+ projectId: project.id,
+ name: "code-template",
+ type: EvalTemplateType.CODE,
+ });
+
+ const ids = await findDefaultModelEvalTemplateIds({
+ tx: prisma,
+ projectId: project.id,
+ });
+
+ expect(ids).toContain(dependentTemplate.id);
+ expect(ids).not.toContain(templateWithOwnModel.id);
+ expect(ids).not.toContain(codeTemplate.id);
+ });
+ });
+
+ describe("findEvalTemplateById", () => {
+ it("returns the template or null", async () => {
+ const project = await prepareProject();
+ const template = await createTemplate({
+ projectId: project.id,
+ name: "find-by-id",
+ });
+
+ await expect(
+ findEvalTemplateById({ tx: prisma, id: template.id }),
+ ).resolves.toMatchObject({ id: template.id, name: "find-by-id" });
+ await expect(
+ findEvalTemplateById({ tx: prisma, id: "non-existent-id" }),
+ ).resolves.toBeNull();
+ });
+ });
+
+ describe("findEvalTemplateFamilyVersions", () => {
+ it("returns all versions of the name+type family within the project", async () => {
+ const project = await prepareProject();
+ const v1 = await createTemplate({
+ projectId: project.id,
+ name: "family",
+ version: 1,
+ });
+ const v2 = await createTemplate({
+ projectId: project.id,
+ name: "family",
+ version: 2,
+ });
+ // same name but different type belongs to another family
+ const codeSibling = await createTemplate({
+ projectId: project.id,
+ name: "family-code",
+ type: EvalTemplateType.CODE,
+ });
+ const otherName = await createTemplate({
+ projectId: project.id,
+ name: "other-family",
+ });
+
+ const versions = await findEvalTemplateFamilyVersions({
+ tx: prisma,
+ projectId: project.id,
+ name: "family",
+ type: EvalTemplateType.LLM_AS_JUDGE,
+ });
+
+ const versionIds = versions.map((version) => version.id);
+ expect(versionIds).toHaveLength(2);
+ expect(versionIds).toEqual(expect.arrayContaining([v1.id, v2.id]));
+ expect(versionIds).not.toContain(codeSibling.id);
+ expect(versionIds).not.toContain(otherName.id);
+ });
+
+ it("resolves langfuse-managed families via null projectId", async () => {
+ const managedName = `managed-family-${Date.now()}`;
+ const managed = await createTemplate({
+ projectId: null,
+ name: managedName,
+ });
+
+ const versions = await findEvalTemplateFamilyVersions({
+ tx: prisma,
+ projectId: null,
+ name: managedName,
+ type: EvalTemplateType.LLM_AS_JUDGE,
+ });
+
+ expect(versions.map((version) => version.id)).toEqual([managed.id]);
+ });
+ });
+
+ describe("findJobConfigurationsReferencingEvalTemplates", () => {
+ it("returns the referencing job configurations of the project", async () => {
+ const project = await prepareProject();
+ const v1 = await createTemplate({
+ projectId: project.id,
+ name: "referenced",
+ version: 1,
+ });
+ const v2 = await createTemplate({
+ projectId: project.id,
+ name: "referenced",
+ version: 2,
+ });
+ const config = await createJobConfiguration({
+ projectId: project.id,
+ evalTemplateId: v1.id,
+ scoreName: "referenced-score",
+ });
+
+ await expect(
+ findJobConfigurationsReferencingEvalTemplates({
+ tx: prisma,
+ projectId: project.id,
+ evalTemplateIds: [v1.id, v2.id],
+ }),
+ ).resolves.toEqual([{ id: config.id, scoreName: "referenced-score" }]);
+
+ await expect(
+ findJobConfigurationsReferencingEvalTemplates({
+ tx: prisma,
+ projectId: project.id,
+ evalTemplateIds: [v2.id],
+ }),
+ ).resolves.toEqual([]);
+ });
+ });
+
+ describe("deleteEvalTemplatesByIds", () => {
+ it("deletes the given templates but never crosses project boundaries", async () => {
+ const project = await prepareProject();
+ const otherProject = await prepareProject();
+ const template = await createTemplate({
+ projectId: project.id,
+ name: "to-delete",
+ });
+ const otherProjectTemplate = await createTemplate({
+ projectId: otherProject.id,
+ name: "to-delete",
+ });
+
+ await deleteEvalTemplatesByIds({
+ tx: prisma,
+ projectId: project.id,
+ evalTemplateIds: [template.id, otherProjectTemplate.id],
+ });
+
+ await expect(
+ prisma.evalTemplate.findUnique({ where: { id: template.id } }),
+ ).resolves.toBeNull();
+ await expect(
+ prisma.evalTemplate.findUnique({
+ where: { id: otherProjectTemplate.id },
+ }),
+ ).resolves.not.toBeNull();
+ });
+ });
+
+ describe("lockEvalTemplateFamilyVersions", () => {
+ // runs on its own pooled connection, so it competes with the
+ // transaction's locks; NOWAIT makes lock contention fail immediately
+ // instead of blocking
+ const lockRowNoWait = (id: string) =>
+ prisma.$queryRaw`SELECT id FROM eval_templates WHERE id = ${id} FOR UPDATE NOWAIT`;
+
+ it("locks every version of the family until the transaction ends", async () => {
+ const project = await prepareProject();
+ const v1 = await createTemplate({
+ projectId: project.id,
+ name: "locked-template",
+ version: 1,
+ });
+ const v2 = await createTemplate({
+ projectId: project.id,
+ name: "locked-template",
+ version: 2,
+ });
+ const unrelatedTemplate = await createTemplate({
+ projectId: project.id,
+ name: "unlocked-template",
+ });
+
+ await prisma.$transaction(async (tx) => {
+ await lockEvalTemplateFamilyVersions({
+ tx,
+ projectId: project.id,
+ name: "locked-template",
+ type: EvalTemplateType.LLM_AS_JUDGE,
+ });
+
+ // no other connection can lock any version of the family
+ await expect(lockRowNoWait(v1.id)).rejects.toThrow(
+ /could not obtain lock/,
+ );
+ await expect(lockRowNoWait(v2.id)).rejects.toThrow(
+ /could not obtain lock/,
+ );
+ // templates outside the family stay lockable
+ await expect(
+ lockRowNoWait(unrelatedTemplate.id),
+ ).resolves.toBeDefined();
+ });
+
+ // locks are released once the transaction commits
+ await expect(lockRowNoWait(v1.id)).resolves.toBeDefined();
+ });
+ });
+});
diff --git a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
index 838cd39fdd..01474ece94 100644
--- a/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
+++ b/web/src/__tests__/server/mcp-public-api-tools.servertest.ts
@@ -235,6 +235,7 @@ describe("MCP public API tools", () => {
"deleteDatasetItem",
"deleteDatasetRun",
"deleteEvaluationRule",
+ "deleteEvaluator",
"deleteModel",
"deleteScoreConfig",
"updateAnnotationQueueItem",
diff --git a/web/src/__tests__/server/mcp-tools-write.servertest.ts b/web/src/__tests__/server/mcp-tools-write.servertest.ts
index 40ceb001a7..3fc21b49d5 100644
--- a/web/src/__tests__/server/mcp-tools-write.servertest.ts
+++ b/web/src/__tests__/server/mcp-tools-write.servertest.ts
@@ -76,6 +76,10 @@ import {
deleteEvaluationRuleTool,
handleDeleteEvaluationRule,
} from "@/src/features/mcp/features/evals/tools/deleteEvaluationRule";
+import {
+ deleteEvaluatorTool,
+ handleDeleteEvaluator,
+} from "@/src/features/mcp/features/evals/tools/deleteEvaluator";
import { handleGetEvaluationRule } from "@/src/features/mcp/features/evals/tools/getEvaluationRule";
const createScoreConfig = async (projectId: string) =>
@@ -332,6 +336,50 @@ describe("MCP Write Tools", () => {
});
});
+ describe("deleteEvaluator tool", () => {
+ it("should have destructiveHint annotation", () => {
+ verifyToolAnnotations(deleteEvaluatorTool, {
+ destructiveHint: true,
+ });
+ });
+
+ it("should delete an evaluator and audit the write", async () => {
+ const setup = await createMcpTestSetup();
+ const { projectId, apiKeyId } = setup;
+ const evaluator = await createLlmEvaluatorForMcpWriteTest(setup);
+
+ await expect(
+ handleDeleteEvaluator({ evaluatorId: evaluator.id }, setup.context),
+ ).resolves.toEqual({ message: "Evaluator successfully deleted" });
+ await expect(
+ verifyAuditLog({
+ projectId,
+ apiKeyId,
+ resourceType: "evalTemplate",
+ resourceId: evaluator.id,
+ action: "delete",
+ }),
+ ).resolves.toMatchObject({ resourceId: evaluator.id, action: "delete" });
+
+ await expect(
+ prisma.evalTemplate.findUnique({ where: { id: evaluator.id } }),
+ ).resolves.toBeNull();
+ });
+
+ it("should reject deletion while an evaluation rule references the evaluator", async () => {
+ const setup = await createMcpTestSetup();
+ const { evaluator } = await createLlmEvaluationRuleForMcpWriteTest(setup);
+
+ await expect(
+ handleDeleteEvaluator({ evaluatorId: evaluator.id }, setup.context),
+ ).rejects.toThrow(/evaluation rule/);
+
+ await expect(
+ prisma.evalTemplate.findUnique({ where: { id: evaluator.id } }),
+ ).resolves.not.toBeNull();
+ });
+ });
+
describe("createAnnotationQueue tool", () => {
it("should create a basic annotation queue", async () => {
const { context, projectId } = await createMcpTestSetup();
diff --git a/web/src/__tests__/server/unit/default-model-eval-template-repository.servertest.ts b/web/src/__tests__/server/unit/default-model-eval-template-repository.servertest.ts
deleted file mode 100644
index 255712c67e..0000000000
--- a/web/src/__tests__/server/unit/default-model-eval-template-repository.servertest.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-import { EvalTemplateType, type Prisma } from "@langfuse/shared/src/db";
-import { findDefaultModelEvalTemplateIds } from "@/src/features/evals/server/defaultModelEvalTemplateRepository";
-
-describe("findDefaultModelEvalTemplateIds", () => {
- it("only selects LLM-as-judge templates that depend on the default model", async () => {
- const findMany = vi.fn().mockResolvedValue([{ id: "template-1" }]);
- const tx = {
- evalTemplate: {
- findMany,
- },
- } as unknown as Prisma.TransactionClient;
-
- await expect(
- findDefaultModelEvalTemplateIds({
- tx,
- projectId: "project-123",
- }),
- ).resolves.toEqual(["template-1"]);
-
- expect(findMany).toHaveBeenCalledWith({
- where: {
- OR: [{ projectId: "project-123" }, { projectId: null }],
- provider: null,
- model: null,
- type: EvalTemplateType.LLM_AS_JUDGE,
- },
- select: {
- id: true,
- },
- });
- });
-});
diff --git a/web/src/__tests__/server/unstable-evals-api.servertest.ts b/web/src/__tests__/server/unstable-evals-api.servertest.ts
index 0388441b63..d81497c515 100644
--- a/web/src/__tests__/server/unstable-evals-api.servertest.ts
+++ b/web/src/__tests__/server/unstable-evals-api.servertest.ts
@@ -8,6 +8,7 @@ import {
PostUnstableEvaluationRuleResponse,
} from "@/src/features/public-api/types/unstable-evaluation-rules";
import {
+ DeleteUnstableEvaluatorResponse,
GetUnstableEvaluatorResponse,
GetUnstableEvaluatorsResponse,
PostUnstableEvaluatorResponse,
@@ -214,6 +215,148 @@ describe("/api/public/unstable evaluators API", () => {
).toBe(false);
});
+ it("deletes an evaluator including all of its versions via any version id", async () => {
+ const v1 = await makeZodVerifiedAPICall(
+ PostUnstableEvaluatorResponse,
+ "POST",
+ "/api/public/unstable/evaluators",
+ {
+ name: "Deletable correctness",
+ prompt: "Judge {{input}} against {{output}}",
+ outputDefinition: numericOutputDefinition,
+ },
+ auth,
+ );
+
+ const v2 = await makeZodVerifiedAPICall(
+ PostUnstableEvaluatorResponse,
+ "POST",
+ "/api/public/unstable/evaluators",
+ {
+ name: "Deletable correctness",
+ prompt: "Judge {{input}} versus {{output}}",
+ outputDefinition: numericOutputDefinition,
+ },
+ auth,
+ );
+
+ // deleting via the old version id removes the whole family
+ const deleted = await makeZodVerifiedAPICall(
+ DeleteUnstableEvaluatorResponse,
+ "DELETE",
+ `/api/public/unstable/evaluators/${v1.body.id}`,
+ undefined,
+ auth,
+ );
+ expect(deleted.body.message).toBe("Evaluator successfully deleted");
+
+ const fetchLatest = await makeAPICall(
+ "GET",
+ `/api/public/unstable/evaluators/${v2.body.id}`,
+ undefined,
+ auth,
+ );
+ expectUnstableError(fetchLatest, {
+ status: 404,
+ code: "resource_not_found",
+ });
+ });
+
+ it("rejects evaluator deletion while evaluation rules reference the family", async () => {
+ const evaluator = await makeZodVerifiedAPICall(
+ PostUnstableEvaluatorResponse,
+ "POST",
+ "/api/public/unstable/evaluators",
+ {
+ name: "Referenced correctness",
+ prompt: "Judge {{input}} against {{output}}",
+ outputDefinition: numericOutputDefinition,
+ },
+ auth,
+ );
+
+ const rule = await makeZodVerifiedAPICall(
+ PostUnstableEvaluationRuleResponse,
+ "POST",
+ "/api/public/unstable/evaluation-rules",
+ {
+ name: "referenced_correctness_live",
+ evaluator: {
+ name: "Referenced correctness",
+ scope: "project",
+ },
+ target: "observation",
+ enabled: true,
+ sampling: 1,
+ filter: [],
+ mapping: [
+ { variable: "input", source: "input" },
+ { variable: "output", source: "output" },
+ ],
+ },
+ auth,
+ );
+
+ const blocked = await makeAPICall(
+ "DELETE",
+ `/api/public/unstable/evaluators/${evaluator.body.id}`,
+ undefined,
+ auth,
+ );
+ const blockedBody = expectUnstableError(blocked, {
+ status: 409,
+ code: "conflict",
+ });
+ expect(blockedBody.message).toContain("evaluation rule");
+
+ await makeZodVerifiedAPICall(
+ DeleteUnstableEvaluationRuleResponse,
+ "DELETE",
+ `/api/public/unstable/evaluation-rules/${rule.body.id}`,
+ undefined,
+ auth,
+ );
+
+ await makeZodVerifiedAPICall(
+ DeleteUnstableEvaluatorResponse,
+ "DELETE",
+ `/api/public/unstable/evaluators/${evaluator.body.id}`,
+ undefined,
+ auth,
+ );
+ });
+
+ it("rejects deletion of langfuse-managed evaluators", async () => {
+ const managed = await createManagedEvaluator({
+ name: "Managed deletable",
+ version: 1,
+ });
+
+ const response = await makeAPICall(
+ "DELETE",
+ `/api/public/unstable/evaluators/${managed.id}`,
+ undefined,
+ auth,
+ );
+ expectUnstableError(response, {
+ status: 403,
+ code: "access_denied",
+ });
+ });
+
+ it("returns 404 when deleting an unknown evaluator", async () => {
+ const response = await makeAPICall(
+ "DELETE",
+ "/api/public/unstable/evaluators/unknown-evaluator-id",
+ undefined,
+ auth,
+ );
+ expectUnstableError(response, {
+ status: 404,
+ code: "resource_not_found",
+ });
+ });
+
it("automatically moves existing evaluation rules to the newest project evaluator version", async () => {
await makeZodVerifiedAPICall(
PostUnstableEvaluatorResponse,
@@ -444,7 +587,7 @@ describe("/api/public/unstable evaluators API", () => {
expect(deleted.body.message).toBe("Evaluation rule successfully deleted");
});
- it("returns method_not_allowed for evaluator patch and delete", async () => {
+ it("returns method_not_allowed for evaluator patch", async () => {
const evaluator = await makeZodVerifiedAPICall(
PostUnstableEvaluatorResponse,
"POST",
@@ -465,21 +608,11 @@ describe("/api/public/unstable evaluators API", () => {
},
auth,
);
- const deleteRes = await makeAPICall(
- "DELETE",
- `/api/public/unstable/evaluators/${evaluator.body.id}`,
- undefined,
- auth,
- );
expectUnstableError(patchRes, {
status: 405,
code: "method_not_allowed",
});
- expectUnstableError(deleteRes, {
- status: 405,
- code: "method_not_allowed",
- });
});
it("still rejects invalid auth with the unstable error envelope", async () => {
diff --git a/web/src/components/deleteButton.tsx b/web/src/components/deleteButton.tsx
index daadd13b7a..2676a0a941 100644
--- a/web/src/components/deleteButton.tsx
+++ b/web/src/components/deleteButton.tsx
@@ -29,6 +29,9 @@ export type DeleteButtonProps = {
variant?: ButtonProps["variant"];
title?: string;
className?: string;
+ // forwarded explicitly because the base component does not spread unknown
+ // props onto the rendered button
+ "aria-label"?: string;
};
type BaseDeleteButtonProps = Omit<DeleteButtonProps, "itemId"> & {
@@ -48,6 +51,9 @@ type BaseDeleteButtonProps = Omit<DeleteButtonProps, "itemId"> & {
executeDeleteMutation: (onSuccess: () => void) => Promise<void>;
isDeleteMutationLoading: boolean;
itemId?: string;
+ // when set, the popover explains why deletion is blocked instead of asking for confirmation
+ deleteBlocker?: React.ReactNode;
+ onPopoverOpenChange?: (open: boolean) => void;
};
export function DeleteButton({
@@ -69,6 +75,9 @@ export function DeleteButton({
executeDeleteMutation,
isDeleteMutationLoading,
customDeletePrompt,
+ deleteBlocker,
+ onPopoverOpenChange,
+ "aria-label": ariaLabel,
}: BaseDeleteButtonProps) {
const [isDeleted, setIsDeleted] = useState(false);
const router = useRouter();
@@ -95,12 +104,13 @@ export function DeleteButton({
]);
return (
- <Popover key={itemId ?? "delete-action"}>
+ <Popover key={itemId ?? "delete-action"} onOpenChange={onPopoverOpenChange}>
<PopoverTrigger asChild>
<Button
variant={variant ?? (icon ? "outline-solid" : "ghost")}
size={icon ? "icon" : "default"}
title={title}
+ aria-label={ariaLabel}
className={className}
disabled={!hasAccess || !enabled}
onClick={(e) => {
@@ -123,43 +133,47 @@ export function DeleteButton({
</Button>
</PopoverTrigger>
<PopoverContent onClick={(e) => e.stopPropagation()}>
- <h2 className="text-md mb-3 font-semibold">Please confirm</h2>
- <p className="mb-3 max-w-72 text-sm">
- {customDeletePrompt ??
- `This action cannot be undone. It removes all the data associated with
+ {deleteBlocker ?? (
+ <>
+ <h2 className="text-md mb-3 font-semibold">Please confirm</h2>
+ <p className="mb-3 max-w-72 text-sm">
+ {customDeletePrompt ??
+ `This action cannot be undone. It removes all the data associated with
this ${entityToDeleteName}. If this is the project default, it will be deleted for all users.`}
- </p>
- {deleteConfirmation && (
- <div className="mb-4 grid w-full gap-1.5">
- <Label htmlFor="delete-confirmation">
- Type &quot;{deleteConfirmation}&quot; to confirm
- </Label>
- <Input
- id="delete-confirmation"
- value={deleteConfirmationInput}
- onChange={(e) => setDeleteConfirmationInput(e.target.value)}
- />
- </div>
+ </p>
+ {deleteConfirmation && (
+ <div className="mb-4 grid w-full gap-1.5">
+ <Label htmlFor="delete-confirmation">
+ Type &quot;{deleteConfirmation}&quot; to confirm
+ </Label>
+ <Input
+ id="delete-confirmation"
+ value={deleteConfirmationInput}
+ onChange={(e) => setDeleteConfirmationInput(e.target.value)}
+ />
+ </div>
+ )}
+ <div className="flex justify-end space-x-4">
+ <Button
+ type="button"
+ variant="destructive"
+ loading={isDeleteMutationLoading || isDeleted}
+ onClick={() => {
+ if (
+ deleteConfirmation &&
+ deleteConfirmationInput !== deleteConfirmation
+ ) {
+ alert("Please type the correct confirmation");
+ return;
+ }
+ executeDeleteMutation(onDeleteSuccess);
+ }}
+ >
+ Delete {entityToDeleteName}
+ </Button>
+ </div>
+ </>
)}
- <div className="flex justify-end space-x-4">
- <Button
- type="button"
- variant="destructive"
- loading={isDeleteMutationLoading || isDeleted}
- onClick={() => {
- if (
- deleteConfirmation &&
- deleteConfirmationInput !== deleteConfirmation
- ) {
- alert("Please type the correct confirmation");
- return;
- }
- executeDeleteMutation(onDeleteSuccess);
- }}
- >
- Delete {entityToDeleteName}
- </Button>
- </div>
</PopoverContent>
</Popover>
);
@@ -461,48 +475,3 @@ export function DeleteEvaluationModelButton(
/>
);
}
-
-// TODO: Moved to LFE-4573
-// export function DeleteEvaluatorTemplateButton(props: DeleteButtonProps) {
-// const utils = api.useUtils();
-// const { itemId, projectId,
-// scope = "evalTemplate:CUD",
-// invalidateFunc = () => void utils.evals.invalidate(),
-// } = props;
-// const templateMutation = api.evals.deleteEvalTemplate.useMutation();
-// const executeDeleteMutation = async (onSuccess: () => void) => {
-// try {
-// await templateMutation.mutateAsync({
-// evalTemplateId: itemId,
-// projectId,
-// });
-// } catch (error) {
-// return Promise.reject(error);
-// }
-// onSuccess();
-// };
-// const hasModelBasedEvaluationEntitlement = useHasEntitlement(
-// "model-based-evaluations",
-// );
-// return (
-// <DeleteButton
-// {...props}
-// scope={scope}
-// invalidateFunc={invalidateFunc}
-// captureDeleteOpen={(capture, isTableAction) =>
-// capture("eval_templates:delete_form_open", {
-// source: isTableAction ? "table-single-row" : "template",
-// })
-// }
-// captureDeleteSuccess={(capture, isTableAction) =>
-// capture("eval_templates:delete_template_button_click", {
-// source: isTableAction ? "table-single-row" : "template",
-// })
-// }
-// entityToDeleteName="template"
-// executeDeleteMutation={executeDeleteMutation}
-// isDeleteMutationLoading={templateMutation.isLoading}
-// enabled={hasModelBasedEvaluationEntitlement}
-// />
-// );
-// }
diff --git a/web/src/features/evals/components/delete-eval-template-button.tsx b/web/src/features/evals/components/delete-eval-template-button.tsx
new file mode 100644
index 0000000000..4d39c34a88
--- /dev/null
+++ b/web/src/features/evals/components/delete-eval-template-button.tsx
@@ -0,0 +1,137 @@
+import {
+ DeleteButton,
+ type DeleteButtonProps,
+} from "@/src/components/deleteButton";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { api } from "@/src/utils/api";
+import { ExternalLinkIcon } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+
+type ReferencingEvaluator = {
+ id: string;
+ scoreName: string;
+};
+
+type DeleteEvalTemplateButtonProps = DeleteButtonProps & {
+ // Usage count from already-loaded table data; lets the blocked state render
+ // instantly while the usage query is in flight.
+ initialUsageCount?: number;
+ // The template name; doubles as the type-to-confirm string.
+ deleteConfirmation: string;
+};
+
+export function DeleteEvalTemplateButton(props: DeleteEvalTemplateButtonProps) {
+ const utils = api.useUtils();
+ const {
+ itemId,
+ projectId,
+ scope = "evalTemplate:CUD",
+ invalidateFunc = () => utils.evals.invalidate(),
+ initialUsageCount,
+ deleteConfirmation: templateName,
+ } = props;
+
+ const templateMutation = api.evals.deleteEvalTemplate.useMutation({
+ onSuccess: () => {
+ showSuccessToast({
+ title: "Evaluator deleted",
+ description: `Evaluator "${templateName}" was deleted.`,
+ });
+ utils.evals.invalidate();
+ },
+ onError: (error) =>
+ showErrorToast("Failed to delete evaluator", error.message),
+ });
+
+ // Only fetch usage once the user actually opens the delete popover. Once
+ // deletion starts, the query must go inactive so post-delete invalidation
+ // does not refetch it and surface a NOT_FOUND.
+ const [hasOpenedPopover, setHasOpenedPopover] = useState(false);
+ const usage = api.evals.evalTemplateUsage.useQuery(
+ { projectId, evalTemplateId: itemId },
+ {
+ enabled:
+ hasOpenedPopover &&
+ !templateMutation.isPending &&
+ !templateMutation.isSuccess,
+ },
+ );
+ const referencingEvaluators = usage.data;
+ const usageCount = referencingEvaluators?.length ?? initialUsageCount ?? 0;
+
+ const executeDeleteMutation = async (onSuccess: () => void) => {
+ try {
+ await templateMutation.mutateAsync({
+ evalTemplateId: itemId,
+ projectId,
+ });
+ onSuccess();
+ } catch {
+ // Surfaced via the mutation's onError toast.
+ }
+ };
+
+ const renderEvaluatorLink = (evaluator: ReferencingEvaluator) => (
+ <Link
+ href={`/project/${projectId}/evals?peek=${evaluator.id}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex items-center gap-1 text-blue-600 hover:underline"
+ >
+ {evaluator.scoreName}
+ <ExternalLinkIcon className="h-3 w-3" />
+ </Link>
+ );
+
+ const deleteBlocker =
+ usageCount > 0 ? (
+ <>
+ <h2 className="text-md mb-3 font-semibold">Cannot delete</h2>
+ <p className="mb-3 max-w-72 text-sm">
+ This evaluator is used by {usageCount} running evaluator
+ {usageCount === 1 ? "" : "s"}. Delete those running evaluators first.
+ </p>
+ {referencingEvaluators && referencingEvaluators.length > 0 ? (
+ referencingEvaluators.length === 1 ? (
+ <div className="max-w-72 text-sm">
+ {renderEvaluatorLink(referencingEvaluators[0])}
+ </div>
+ ) : (
+ <ul className="max-h-40 max-w-72 list-inside list-disc overflow-y-auto text-sm">
+ {referencingEvaluators.map((evaluator) => (
+ <li key={evaluator.id}>{renderEvaluatorLink(evaluator)}</li>
+ ))}
+ </ul>
+ )
+ ) : null}
+ </>
+ ) : undefined;
+
+ return (
+ <DeleteButton
+ {...props}
+ scope={scope}
+ invalidateFunc={invalidateFunc}
+ captureDeleteOpen={(capture, isTableAction) =>
+ capture("eval_templates:delete_form_open", {
+ source: isTableAction ? "table-single-row" : "template",
+ })
+ }
+ captureDeleteSuccess={(capture, isTableAction) =>
+ capture("eval_templates:delete_template_button_click", {
+ source: isTableAction ? "table-single-row" : "template",
+ })
+ }
+ entityToDeleteName="evaluator"
+ customDeletePrompt="This action cannot be undone. It permanently deletes all versions of this evaluator. Scores already produced by it will not be deleted."
+ executeDeleteMutation={executeDeleteMutation}
+ isDeleteMutationLoading={templateMutation.isPending}
+ deleteBlocker={deleteBlocker}
+ onPopoverOpenChange={(open) => {
+ if (open) setHasOpenedPopover(true);
+ }}
+ />
+ );
+}
diff --git a/web/src/features/evals/components/eval-template-detail.tsx b/web/src/features/evals/components/eval-template-detail.tsx
index c9ebe213e8..593a6e8953 100644
--- a/web/src/features/evals/components/eval-template-detail.tsx
+++ b/web/src/features/evals/components/eval-template-detail.tsx
@@ -25,6 +25,7 @@ import {
SidePanelTitle,
} from "@/src/components/ui/side-panel";
import { LangfuseIcon } from "@/src/components/LangfuseLogo";
+import { DeleteEvalTemplateButton } from "@/src/features/evals/components/delete-eval-template-button";
export const EvalTemplateDetail = () => {
const router = useRouter();
@@ -106,18 +107,15 @@ export const EvalTemplateDetail = () => {
isCustom={!!template.data?.projectId}
/>
- {/* TODO: moved to LFE-4573 */}
- {/* <DeleteEvaluatorTemplateButton
- itemId={templateId}
- projectId={projectId}
- redirectUrl={`/project/${projectId}/evals/templates`}
- deleteConfirmation={
- template.data != null
- ? `${template.data.name}-v${template.data.version}`
- : undefined
- }
- enabled={!template.isPending}
- /> */}
+ {template.data?.projectId ? (
+ <DeleteEvalTemplateButton
+ itemId={templateId}
+ projectId={projectId}
+ icon
+ redirectUrl={`/project/${projectId}/evals/templates`}
+ deleteConfirmation={template.data.name}
+ />
+ ) : null}
</>
),
}}
diff --git a/web/src/features/evals/components/eval-templates-table.tsx b/web/src/features/evals/components/eval-templates-table.tsx
index 6681316bf2..1e62c0a866 100644
--- a/web/src/features/evals/components/eval-templates-table.tsx
+++ b/web/src/features/evals/components/eval-templates-table.tsx
@@ -6,7 +6,7 @@ import useColumnVisibility from "@/src/features/column-visibility/hooks/useColum
import { type RouterOutputs, api } from "@/src/utils/api";
import { safeExtract } from "@/src/utils/map-utils";
import { createColumnHelper } from "@tanstack/react-table";
-import { Copy, Pen } from "lucide-react";
+import { Copy, MoreVertical, Pen } from "lucide-react";
import { useQueryParam, StringParam, withDefault } from "use-query-params";
import { useEffect, useMemo, useState } from "react";
import { usePaginationState } from "@/src/hooks/usePaginationState";
@@ -24,6 +24,14 @@ import {
DialogHeader,
DialogTitle,
} from "@/src/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuTrigger,
+} from "@/src/components/ui/dropdown-menu";
+import { DeleteEvalTemplateButton } from "@/src/features/evals/components/delete-eval-template-button";
import { EvalTemplateForm } from "@/src/features/evals/components/template-form";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { EvalReferencedEvaluators } from "@/src/features/evals/types";
@@ -330,9 +338,10 @@ export default function EvalsTemplateTable({
const isInvalid = isTemplateInvalid(row.original);
const isCodeTemplate = row.original.type === EvalTemplateType.CODE;
const isUserMaintained = row.original.maintainer.includes("User");
+ const hasMenuItems = isUserMaintained || !isCodeTemplate;
return (
- <div className="flex flex-row gap-2">
+ <div className="flex flex-row items-center gap-2">
<ActionButton
variant="outline"
size="sm"
@@ -357,35 +366,60 @@ export default function EvalsTemplateTable({
>
Use Evaluator
</ActionButton>
- {!isUserMaintained && !isCodeTemplate ? (
- <Button
- aria-label="clone"
- variant="outline"
- size="icon-xs"
- title="Clone"
- disabled={!hasAccess}
- onClick={(e) => {
- e.stopPropagation();
- if (id) setCloneTemplateId(id);
- }}
- >
- <Copy className="h-3 w-3" />
- </Button>
- ) : null}
- {isUserMaintained ? (
- <Button
- aria-label="edit"
- variant="outline"
- size="icon-xs"
- title="Edit"
- disabled={!hasAccess}
- onClick={(e) => {
- e.stopPropagation();
- if (id) setEditTemplateId(id);
- }}
- >
- <Pen className="h-3 w-3" />
- </Button>
+ {hasMenuItems && id ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-xs" aria-label="actions">
+ <span className="sr-only relative">Open menu</span>
+ <MoreVertical className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ {!isUserMaintained && !isCodeTemplate ? (
+ <DropdownMenuItem
+ aria-label="clone"
+ disabled={!hasAccess}
+ onClick={(e) => {
+ e.stopPropagation();
+ setCloneTemplateId(id);
+ }}
+ >
+ <Copy className="mr-2 h-4 w-4" />
+ Clone
+ </DropdownMenuItem>
+ ) : null}
+ {isUserMaintained ? (
+ <>
+ <DropdownMenuItem
+ aria-label="edit"
+ disabled={!hasAccess}
+ onClick={(e) => {
+ e.stopPropagation();
+ setEditTemplateId(id);
+ }}
+ >
+ <Pen className="mr-2 h-4 w-4" />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem asChild>
+ <DeleteEvalTemplateButton
+ aria-label="delete"
+ itemId={id}
+ projectId={projectId}
+ isTableAction
+ className="w-full justify-start"
+ deleteConfirmation={row.original.name}
+ initialUsageCount={row.original.usageCount}
+ invalidateFunc={() => {
+ utils.evals.templateNames.invalidate();
+ }}
+ />
+ </DropdownMenuItem>
+ </>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
) : null}
</div>
);
@@ -411,7 +445,7 @@ export default function EvalsTemplateTable({
detailNavigationKey: "eval-templates",
peekEventOptions: {
ignoredSelectors: [
- "[aria-label='apply'], [aria-label='actions'], [aria-label='edit'], [aria-label='clone']",
+ "[aria-label='apply'], [aria-label='actions'], [aria-label='edit'], [aria-label='clone'], [aria-label='delete']",
],
},
...peekNavigationProps,
@@ -461,7 +495,9 @@ export default function EvalsTemplateTable({
tableName={"evalTemplates"}
columns={columns}
peekView={peekConfig}
- rowHeight="m"
+ // "s" vertically centers cell content; the custom heights keep the
+ // row at h-8 regardless
+ rowHeight="s"
customRowHeights={templateTableRowHeights}
data={
templates.isLoading
diff --git a/web/src/features/evals/server/defaultEvalModelRouter.ts b/web/src/features/evals/server/defaultEvalModelRouter.ts
index 427e2ffdc6..4ca12e9c6d 100644
--- a/web/src/features/evals/server/defaultEvalModelRouter.ts
+++ b/web/src/features/evals/server/defaultEvalModelRouter.ts
@@ -4,7 +4,7 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { z } from "zod";
-import { findDefaultModelEvalTemplateIds } from "./defaultModelEvalTemplateRepository";
+import { findDefaultModelEvalTemplateIds } from "./evaluatorRepository";
import {
EvaluatorBlockReason,
ZodModelConfig,
diff --git a/web/src/features/evals/server/defaultModelEvalTemplateRepository.ts b/web/src/features/evals/server/defaultModelEvalTemplateRepository.ts
deleted file mode 100644
index 2c1238618c..0000000000
--- a/web/src/features/evals/server/defaultModelEvalTemplateRepository.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { EvalTemplateType, type Prisma } from "@langfuse/shared/src/db";
-
-export async function findDefaultModelEvalTemplateIds({
- tx,
- projectId,
-}: {
- tx: Prisma.TransactionClient;
- projectId: string;
-}) {
- const evalTemplates = await tx.evalTemplate.findMany({
- where: {
- OR: [{ projectId }, { projectId: null }],
- provider: null,
- model: null,
- type: EvalTemplateType.LLM_AS_JUDGE,
- },
- select: {
- id: true,
- },
- });
-
- return evalTemplates.map((template) => template.id);
-}
diff --git a/web/src/features/evals/server/evalTemplateDeletion.ts b/web/src/features/evals/server/evalTemplateDeletion.ts
new file mode 100644
index 0000000000..00d807aecf
--- /dev/null
+++ b/web/src/features/evals/server/evalTemplateDeletion.ts
@@ -0,0 +1,180 @@
+import { type PrismaClient } from "@prisma/client";
+import {
+ ForbiddenError,
+ LangfuseConflictError,
+ LangfuseNotFoundError,
+} from "@langfuse/shared";
+import { type ApiAccessScope } from "@langfuse/shared/src/server";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";
+import {
+ deleteEvalTemplatesByIds,
+ findEvalTemplateById,
+ findEvalTemplateFamilyVersions,
+ findJobConfigurationsReferencingEvalTemplates,
+ lockEvalTemplateFamilyVersions,
+} from "@/src/features/evals/server/evaluatorRepository";
+
+const MAX_REFERENCING_EVALUATORS_IN_ERROR = 5;
+
+/**
+ * Running evaluators (job configs) of the project that reference any version
+ * of the template's family. Used to warn before the delete is attempted;
+ * deleteEvalTemplateFamily re-checks transactionally.
+ */
+export async function findEvalTemplateFamilyUsage({
+ prisma,
+ projectId,
+ evalTemplateId,
+}: {
+ prisma: PrismaClient;
+ projectId: string;
+ evalTemplateId: string;
+}) {
+ const template = await findEvalTemplateById({
+ tx: prisma,
+ id: evalTemplateId,
+ });
+
+ if (!template || (template.projectId && template.projectId !== projectId)) {
+ throw new LangfuseNotFoundError("Evaluator not found");
+ }
+
+ const versions = await findEvalTemplateFamilyVersions({
+ tx: prisma,
+ projectId: template.projectId,
+ name: template.name,
+ type: template.type,
+ });
+
+ return findJobConfigurationsReferencingEvalTemplates({
+ tx: prisma,
+ projectId,
+ evalTemplateIds: versions.map((version) => version.id),
+ });
+}
+
+/**
+ * Deletes all versions of a project-owned eval template, identified by any
+ * version id of the family.
+ *
+ * Deletion is blocked while any job configuration still references a version,
+ * so configs never end up with a dangling template reference (the FK is
+ * ON DELETE SET NULL and such configs fail at execution time).
+ */
+export async function deleteEvalTemplateFamily({
+ prisma,
+ projectId,
+ evalTemplateId,
+ auditScope,
+ referencingEntityName = "running evaluator",
+}: {
+ prisma: PrismaClient;
+ projectId: string;
+ evalTemplateId: string;
+ // for API-key callers (public API, MCP); tRPC logs with the user session
+ // at the router level instead, like its sibling mutations
+ auditScope?: Pick<ApiAccessScope, "orgId" | "apiKeyId">;
+ // job configs are "running evaluators" in the UI but "evaluation rules" in
+ // the public API contract; the conflict message must match the surface
+ referencingEntityName?: string;
+}) {
+ const template = await findEvalTemplateById({
+ tx: prisma,
+ id: evalTemplateId,
+ });
+
+ if (!template || (template.projectId && template.projectId !== projectId)) {
+ throw new LangfuseNotFoundError("Evaluator not found");
+ }
+
+ if (!template.projectId) {
+ throw new ForbiddenError("Langfuse-managed evaluators cannot be deleted");
+ }
+
+ // Resolve versions and check references inside one transaction so the
+ // reference check and the delete see a consistent snapshot.
+ const deletedVersions = await prisma.$transaction(async (tx) => {
+ // lock first: blocks concurrent rule creation (FK takes FOR KEY SHARE on
+ // the template row) from slipping in between the check and the delete
+ await lockEvalTemplateFamilyVersions({
+ tx,
+ projectId,
+ name: template.name,
+ type: template.type,
+ });
+
+ const versions = await findEvalTemplateFamilyVersions({
+ tx,
+ projectId,
+ name: template.name,
+ type: template.type,
+ });
+ const versionIds = versions.map((version) => version.id);
+
+ const referencingConfigs =
+ await findJobConfigurationsReferencingEvalTemplates({
+ tx,
+ projectId,
+ evalTemplateIds: versionIds,
+ });
+
+ if (referencingConfigs.length > 0) {
+ throw new LangfuseConflictError(
+ buildInUseErrorMessage(
+ template.name,
+ referencingConfigs,
+ referencingEntityName,
+ ),
+ );
+ }
+
+ await deleteEvalTemplatesByIds({
+ tx,
+ projectId,
+ evalTemplateIds: versionIds,
+ });
+
+ return versions;
+ });
+
+ if (auditScope) {
+ await Promise.all(
+ deletedVersions.map((version) =>
+ auditLog({
+ action: "delete",
+ resourceType: EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE,
+ resourceId: version.id,
+ projectId,
+ orgId: auditScope.orgId,
+ apiKeyId: auditScope.apiKeyId,
+ before: version,
+ }),
+ ),
+ );
+ }
+
+ return deletedVersions;
+}
+
+function buildInUseErrorMessage(
+ templateName: string,
+ referencingConfigs: { scoreName: string }[],
+ referencingEntityName: string,
+) {
+ const scoreNames = [
+ ...new Set(referencingConfigs.map((config) => config.scoreName)),
+ ];
+ const shownNames = scoreNames
+ .slice(0, MAX_REFERENCING_EVALUATORS_IN_ERROR)
+ .map((name) => `"${name}"`)
+ .join(", ");
+ const overflow =
+ scoreNames.length > MAX_REFERENCING_EVALUATORS_IN_ERROR
+ ? ` and ${scoreNames.length - MAX_REFERENCING_EVALUATORS_IN_ERROR} more`
+ : "";
+
+ // count unique score names, not raw configs: several configs can share a
+ // score name and the count must match the listed names
+ return `Evaluator "${templateName}" is in use by ${scoreNames.length} ${referencingEntityName}(s): ${shownNames}${overflow}. Delete those ${referencingEntityName}s first.`;
+}
diff --git a/web/src/features/evals/server/evaluatorRepository.ts b/web/src/features/evals/server/evaluatorRepository.ts
new file mode 100644
index 0000000000..5e4e2717a5
--- /dev/null
+++ b/web/src/features/evals/server/evaluatorRepository.ts
@@ -0,0 +1,119 @@
+import { EvalTemplateType, Prisma } from "@langfuse/shared/src/db";
+
+/**
+ * Data access for eval templates ("evaluators" in the public naming).
+ * All functions take a `tx` so callers can compose them inside transactions;
+ * pass the plain prisma client when no transaction is needed.
+ */
+
+export async function findDefaultModelEvalTemplateIds({
+ tx,
+ projectId,
+}: {
+ tx: Prisma.TransactionClient;
+ projectId: string;
+}) {
+ const evalTemplates = await tx.evalTemplate.findMany({
+ where: {
+ OR: [{ projectId }, { projectId: null }],
+ provider: null,
+ model: null,
+ type: EvalTemplateType.LLM_AS_JUDGE,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ return evalTemplates.map((template) => template.id);
+}
+
+export async function findEvalTemplateById({
+ tx,
+ id,
+}: {
+ tx: Prisma.TransactionClient;
+ id: string;
+}) {
+ return tx.evalTemplate.findUnique({ where: { id } });
+}
+
+/**
+ * All versions of a template family. A family is (projectId, name, type) —
+ * the same grouping the evaluator library table uses for versioning.
+ */
+export async function findEvalTemplateFamilyVersions({
+ tx,
+ projectId,
+ name,
+ type,
+}: {
+ tx: Prisma.TransactionClient;
+ // null resolves the versions of a Langfuse-managed (global) family
+ projectId: string | null;
+ name: string;
+ type: EvalTemplateType;
+}) {
+ return tx.evalTemplate.findMany({
+ where: { projectId, name, type },
+ });
+}
+
+/**
+ * Locks all versions of a template family (FOR UPDATE) for the rest of the
+ * transaction. Concurrent job-configuration inserts take FOR KEY SHARE on the
+ * referenced template row via the FK, which conflicts with this lock — so a
+ * rule created concurrently is either visible to a subsequent reference check
+ * or fails its FK once the delete commits.
+ */
+export async function lockEvalTemplateFamilyVersions({
+ tx,
+ projectId,
+ name,
+ type,
+}: {
+ tx: Prisma.TransactionClient;
+ projectId: string;
+ name: string;
+ type: EvalTemplateType;
+}) {
+ await tx.$queryRaw(
+ Prisma.sql`
+ SELECT id
+ FROM eval_templates
+ WHERE project_id = ${projectId}
+ AND name = ${name}
+ AND type = ${type}::"EvalTemplateType"
+ FOR UPDATE
+ `,
+ );
+}
+
+export async function findJobConfigurationsReferencingEvalTemplates({
+ tx,
+ projectId,
+ evalTemplateIds,
+}: {
+ tx: Prisma.TransactionClient;
+ projectId: string;
+ evalTemplateIds: string[];
+}) {
+ return tx.jobConfiguration.findMany({
+ where: { projectId, evalTemplateId: { in: evalTemplateIds } },
+ select: { id: true, scoreName: true },
+ });
+}
+
+export async function deleteEvalTemplatesByIds({
+ tx,
+ projectId,
+ evalTemplateIds,
+}: {
+ tx: Prisma.TransactionClient;
+ projectId: string;
+ evalTemplateIds: string[];
+}) {
+ await tx.evalTemplate.deleteMany({
+ where: { projectId, id: { in: evalTemplateIds } },
+ });
+}
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index d03b18ebc8..a6f44d0686 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -78,6 +78,10 @@ import {
CreateEvalTemplateInputSchema,
validateEvalTemplateCreation,
} from "@/src/features/evals/server/evalTemplateCreation";
+import {
+ deleteEvalTemplateFamily,
+ findEvalTemplateFamilyUsage,
+} from "@/src/features/evals/server/evalTemplateDeletion";
import { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
import {
getCodeEvalCapabilities,
@@ -1628,52 +1632,49 @@ export const evalRouter = createTRPCRouter({
await invalidateProjectEvalConfigCaches(projectId);
}),
- // TODO: moved to LFE-4573
- // deleteEvalTemplate: protectedProjectProcedure
- // .input(z.object({ projectId: z.string(), evalTemplateId: z.string() }))
- // .mutation(async ({ ctx, input: { projectId, evalTemplateId } }) => {
- // throwIfNoEntitlement({
- // entitlement: "model-based-evaluations",
- // projectId: projectId,
- // sessionUser: ctx.session.user,
- // });
- // throwIfNoProjectAccess({
- // session: ctx.session,
- // projectId: projectId,
- // scope: "evalTemplate:CUD",
- // });
-
- // const existingTemplate = await ctx.prisma.evalTemplate.findUnique({
- // where: {
- // id: evalTemplateId,
- // projectId: projectId,
- // },
- // });
-
- // if (!existingTemplate) {
- // logger.warn(
- // `Template for deletion not found for project ${projectId} and id ${evalTemplateId}`,
- // );
- // throw new TRPCError({
- // code: "NOT_FOUND",
- // message: "Template not found",
- // });
- // }
-
- // await auditLog({
- // session: ctx.session,
- // resourceType: "evalTemplate",
- // resourceId: evalTemplateId,
- // action: "delete",
- // });
-
- // await ctx.prisma.evalTemplate.delete({
- // where: {
- // id: evalTemplateId,
- // projectId: projectId,
- // },
- // });
- // }),
+ evalTemplateUsage: protectedProjectProcedure
+ .input(z.object({ projectId: z.string(), evalTemplateId: z.string() }))
+ .query(async ({ ctx, input: { projectId, evalTemplateId } }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: projectId,
+ scope: "evalJob:read",
+ });
+
+ return findEvalTemplateFamilyUsage({
+ prisma: ctx.prisma,
+ projectId,
+ evalTemplateId,
+ });
+ }),
+
+ deleteEvalTemplate: protectedProjectProcedure
+ .input(z.object({ projectId: z.string(), evalTemplateId: z.string() }))
+ .mutation(async ({ ctx, input: { projectId, evalTemplateId } }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: projectId,
+ scope: "evalTemplate:CUD",
+ });
+
+ const deletedVersions = await deleteEvalTemplateFamily({
+ prisma: ctx.prisma,
+ projectId,
+ evalTemplateId,
+ });
+
+ await Promise.all(
+ deletedVersions.map((version) =>
+ auditLog({
+ session: ctx.session,
+ resourceType: EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE,
+ resourceId: version.id,
+ action: "delete",
+ before: version,
+ }),
+ ),
+ );
+ }),
getLogs: protectedProjectProcedure
.input(
z.object({
diff --git a/web/src/features/evals/server/unstable-public-api/evaluator-service.ts b/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
index 8e1ae4aa74..2a6849c177 100644
--- a/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
+++ b/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
@@ -22,6 +22,7 @@ import {
import { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";
+import { deleteEvalTemplateFamily } from "@/src/features/evals/server/evalTemplateDeletion";
import {
toApiEvaluator,
toStoredEvaluatorType,
@@ -345,3 +346,19 @@ export async function createPublicEvaluator(params: {
throw error;
}
}
+
+export async function deletePublicEvaluator(params: {
+ projectId: string;
+ evaluatorId: string;
+ auditScope?: Pick<ApiAccessScope, "orgId" | "apiKeyId">;
+}) {
+ // an evaluator in the public contract is the whole family; deleting it
+ // removes all stored versions
+ await deleteEvalTemplateFamily({
+ prisma,
+ projectId: params.projectId,
+ evalTemplateId: params.evaluatorId,
+ auditScope: params.auditScope,
+ referencingEntityName: "evaluation rule",
+ });
+}
diff --git a/web/src/features/evals/server/unstable-public-api/index.ts b/web/src/features/evals/server/unstable-public-api/index.ts
index c2a8f3c2ad..efec33996f 100644
--- a/web/src/features/evals/server/unstable-public-api/index.ts
+++ b/web/src/features/evals/server/unstable-public-api/index.ts
@@ -7,6 +7,7 @@ export {
} from "./evaluation-rule-service";
export {
createPublicEvaluator,
+ deletePublicEvaluator,
getPublicEvaluator,
listPublicEvaluators,
} from "./evaluator-service";
diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.ts
index 6336af6ec6..8dfb60de8c 100644
--- a/web/src/features/llm-api-key/server/router.ts
+++ b/web/src/features/llm-api-key/server/router.ts
@@ -28,7 +28,7 @@ import {
getEvaluatorBlockMetadata,
type LLMConnectionConfig,
} from "@langfuse/shared";
-import { findDefaultModelEvalTemplateIds } from "@/src/features/evals/server/defaultModelEvalTemplateRepository";
+import { findDefaultModelEvalTemplateIds } from "@/src/features/evals/server/evaluatorRepository";
import { encrypt, decrypt } from "@langfuse/shared/encryption";
import {
ChatMessageType,
diff --git a/web/src/features/mcp/features/evals/index.ts b/web/src/features/mcp/features/evals/index.ts
index 20da4a70b3..4351d9f6f5 100644
--- a/web/src/features/mcp/features/evals/index.ts
+++ b/web/src/features/mcp/features/evals/index.ts
@@ -8,6 +8,10 @@ import {
upsertEvaluatorTool,
handleUpsertEvaluator,
} from "./tools/upsertEvaluator";
+import {
+ deleteEvaluatorTool,
+ handleDeleteEvaluator,
+} from "./tools/deleteEvaluator";
import {
listEvaluationRulesTool,
handleListEvaluationRules,
@@ -45,6 +49,10 @@ export const evalsFeature: McpFeatureModule = {
allowInAppAgentKey: true,
},
{ definition: upsertEvaluatorTool, handler: handleUpsertEvaluator },
+ {
+ definition: deleteEvaluatorTool,
+ handler: handleDeleteEvaluator,
+ },
{
definition: listEvaluationRulesTool,
handler: handleListEvaluationRules,
diff --git a/web/src/features/mcp/features/evals/tools/deleteEvaluator.ts b/web/src/features/mcp/features/evals/tools/deleteEvaluator.ts
new file mode 100644
index 0000000000..30e19d5ce2
--- /dev/null
+++ b/web/src/features/mcp/features/evals/tools/deleteEvaluator.ts
@@ -0,0 +1,33 @@
+import {
+ DeleteUnstableEvaluatorQuery,
+ DeleteUnstableEvaluatorResponse,
+} from "@/src/features/public-api/types/unstable-evaluators";
+import { deletePublicEvaluator } from "@/src/features/evals/server/unstable-public-api";
+import { defineTool } from "../../../core/define-tool";
+import { runMcpTool } from "../../../core/run-mcp-tool";
+
+export const [deleteEvaluatorTool, handleDeleteEvaluator] = defineTool({
+ name: "deleteEvaluator",
+ description:
+ "Delete a project evaluator by id, including all of its versions. Fails while evaluation rules still reference the evaluator; delete those first. Langfuse-managed evaluators cannot be deleted. This cannot be undone.",
+ baseSchema: DeleteUnstableEvaluatorQuery,
+ inputSchema: DeleteUnstableEvaluatorQuery,
+ handler: async (input, context) =>
+ runMcpTool({
+ spanName: "mcp.evaluators.delete",
+ context,
+ attributes: { "mcp.evaluator_id": input.evaluatorId },
+ fn: async () => {
+ await deletePublicEvaluator({
+ projectId: context.projectId,
+ evaluatorId: input.evaluatorId,
+ auditScope: context,
+ });
+
+ return DeleteUnstableEvaluatorResponse.parse({
+ message: "Evaluator successfully deleted",
+ });
+ },
+ }),
+ destructiveHint: true,
+});
diff --git a/web/src/features/public-api/server/unstable-public-api-error-contract.ts b/web/src/features/public-api/server/unstable-public-api-error-contract.ts
index aeb086e186..4ff2515843 100644
--- a/web/src/features/public-api/server/unstable-public-api-error-contract.ts
+++ b/web/src/features/public-api/server/unstable-public-api-error-contract.ts
@@ -4,6 +4,7 @@ import {
BaseError,
InvalidRequestError,
InternalServerError,
+ ForbiddenError,
LangfuseConflictError,
LangfuseNotFoundError,
MethodNotAllowedError,
@@ -184,6 +185,14 @@ export function toUnstablePublicApiError(
});
}
+ if (error instanceof ForbiddenError) {
+ return createUnstablePublicApiError({
+ httpCode: 403,
+ code: "access_denied",
+ message: error.message,
+ });
+ }
+
if (error instanceof MethodNotAllowedError) {
return createUnstablePublicApiError({
httpCode: 405,
diff --git a/web/src/features/public-api/types/unstable-evaluators.ts b/web/src/features/public-api/types/unstable-evaluators.ts
index ec7dba7796..aedf724396 100644
--- a/web/src/features/public-api/types/unstable-evaluators.ts
+++ b/web/src/features/public-api/types/unstable-evaluators.ts
@@ -58,6 +58,14 @@ export const GetUnstableEvaluatorQuery = z.object({
export const GetUnstableEvaluatorResponse = APIEvaluator;
+export const DeleteUnstableEvaluatorQuery = GetUnstableEvaluatorQuery;
+
+export const DeleteUnstableEvaluatorResponse = z
+ .object({
+ message: z.literal("Evaluator successfully deleted"),
+ })
+ .strict();
+
// Fields shared by every create body, regardless of evaluator type. Exported so
// non-route consumers (e.g. the MCP tool layer) reuse the same definition.
export const EvaluatorCreateBase = {
diff --git a/web/src/pages/api/public/llm-connections/[id].ts b/web/src/pages/api/public/llm-connections/[id].ts
index cd9e36ae0f..4340223488 100644
--- a/web/src/pages/api/public/llm-connections/[id].ts
+++ b/web/src/pages/api/public/llm-connections/[id].ts
@@ -16,7 +16,7 @@ import {
EvaluatorBlockSource,
finalizeBlockedEvaluatorConfigBlocks,
} from "@langfuse/shared/src/server";
-import { findDefaultModelEvalTemplateIds } from "@/src/features/evals/server/defaultModelEvalTemplateRepository";
+import { findDefaultModelEvalTemplateIds } from "@/src/features/evals/server/evaluatorRepository";
export default withMiddlewares({
DELETE: createAuthedProjectAPIRoute({
diff --git a/web/src/pages/api/public/unstable/evaluators/[evaluatorId].ts b/web/src/pages/api/public/unstable/evaluators/[evaluatorId].ts
index 6164841926..d4b3db880b 100644
--- a/web/src/pages/api/public/unstable/evaluators/[evaluatorId].ts
+++ b/web/src/pages/api/public/unstable/evaluators/[evaluatorId].ts
@@ -1,9 +1,14 @@
-import { getPublicEvaluator } from "@/src/features/evals/server/unstable-public-api";
+import {
+ deletePublicEvaluator,
+ getPublicEvaluator,
+} from "@/src/features/evals/server/unstable-public-api";
import {
createUnstablePublicEvalsRoute,
withUnstablePublicEvalsMiddlewares,
} from "@/src/features/public-api/server/unstable-public-evals-route";
import {
+ DeleteUnstableEvaluatorQuery,
+ DeleteUnstableEvaluatorResponse,
GetUnstableEvaluatorQuery,
GetUnstableEvaluatorResponse,
} from "@/src/features/public-api/types/unstable-evaluators";
@@ -19,4 +24,20 @@ export default withUnstablePublicEvalsMiddlewares({
evaluatorId: query.evaluatorId,
}),
}),
+ DELETE: createUnstablePublicEvalsRoute({
+ name: "Delete Unstable Evaluator",
+ querySchema: DeleteUnstableEvaluatorQuery,
+ responseSchema: DeleteUnstableEvaluatorResponse,
+ fn: async ({ query, auth }) => {
+ await deletePublicEvaluator({
+ projectId: auth.scope.projectId,
+ evaluatorId: query.evaluatorId,
+ auditScope: auth.scope,
+ });
+
+ return {
+ message: "Evaluator successfully deleted" as const,
+ };
+ },
+ }),
});