🪢 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(api): DELETE endpoint for prompts (#7704)
Domakonda SaiSharan34f9f0aa1789
diff --git a/fern/apis/server/definition/prompts.yml b/fern/apis/server/definition/prompts.ymlindex 68859d21a5..3bb85b06e5 100644--- a/fern/apis/server/definition/prompts.yml+++ b/fern/apis/server/definition/prompts.yml@@ -2,6 +2,7 @@imports:commons: ./commons.ymlpagination: ./utils/pagination.yml+ scim: ./scim.ymlservice:auth: truebase-path: /api/public/v2@@ -59,6 +60,25 @@ service:request: CreatePromptRequestresponse: Prompt+ delete:+ docs: Delete a prompt or specific versions+ method: DELETE+ path: /prompts/{promptName}+ path-parameters:+ promptName:+ type: string+ docs: The name of the prompt+ request:+ name: DeletePromptRequest+ query-parameters:+ label:+ type: optional<string>+ docs: Optional label of the prompt to delete+ version:+ type: optional<integer>+ docs: Optional version of the prompt to delete+ response: scim.EmptyResponse+types:PromptMetaListResponse:properties:diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex eda4b448c5..db73880efc 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -3608,6 +3608,66 @@ paths:schema: {}security:- BasicAuth: []+ delete:+ description: Delete a prompt or specific versions+ operationId: prompts_delete+ tags:+ - Prompts+ parameters:+ - name: promptName+ in: path+ description: The name of the prompt+ required: true+ schema:+ type: string+ - name: label+ in: query+ description: Optional label of the prompt to delete+ required: false+ schema:+ type: string+ nullable: true+ - name: version+ in: query+ description: Optional version of the prompt to delete+ required: false+ schema:+ type: integer+ nullable: true+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/EmptyResponse'+ '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:+ - BasicAuth: []/api/public/v2/prompts:get:description: Get a list of prompt names with versions and labelsdiff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex e29ee846b1..2e0437af4c 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -2650,6 +2650,50 @@}},"response": []+ },+ {+ "_type": "endpoint",+ "name": "Delete",+ "request": {+ "description": "Delete a prompt or specific versions",+ "url": {+ "raw": "{{baseUrl}}/api/public/v2/prompts/:promptName?label=&version=",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "v2",+ "prompts",+ ":promptName"+ ],+ "query": [+ {+ "key": "label",+ "value": "",+ "description": "Optional label of the prompt to delete"+ },+ {+ "key": "version",+ "value": "",+ "description": "Optional version of the prompt to delete"+ }+ ],+ "variable": [+ {+ "key": "promptName",+ "value": "",+ "description": "The name of the prompt"+ }+ ]+ },+ "header": [],+ "method": "DELETE",+ "auth": null,+ "body": null+ },+ "response": []}]},diff --git a/web/src/__tests__/async/prompts.v2.servertest.ts b/web/src/__tests__/async/prompts.v2.servertest.tsindex a53fc93d2f..3d646b0f9c 100644--- a/web/src/__tests__/async/prompts.v2.servertest.ts+++ b/web/src/__tests__/async/prompts.v2.servertest.ts@@ -2813,6 +2813,205 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {}, 10_000);});+ describe("DELETE /api/public/v2/prompts/:promptName", () => {+ it("deletes all versions of a prompt", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ const name = "deletePrompt" + uuidv4();+ await prisma.prompt.createMany({+ data: [+ {+ id: uuidv4(),+ name,+ prompt: "p1",+ labels: ["production"],+ version: 1,+ projectId,+ createdBy: "user",+ config: {},+ type: "TEXT",+ },+ {+ id: uuidv4(),+ name,+ prompt: "p2",+ labels: [],+ version: 2,+ projectId,+ createdBy: "user",+ config: {},+ type: "TEXT",+ },+ ],+ });++ const res = await makeAPICall(+ "DELETE",+ `${baseURI}/${encodeURIComponent(name)}`,+ undefined,+ auth,+ );+ expect(res.status).toBe(204);++ const remaining = await prisma.prompt.findMany({+ where: { projectId, name },+ });+ expect(remaining.length).toBe(0);+ });++ it("deletes by label and version", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ const name = "deletePromptFiltered" + uuidv4();+ await prisma.prompt.createMany({+ data: [+ {+ id: uuidv4(),+ name,+ prompt: "p1",+ labels: ["production"],+ version: 1,+ projectId,+ createdBy: "user",+ config: {},+ type: "TEXT",+ },+ {+ id: uuidv4(),+ name,+ prompt: "p2",+ labels: ["dev"],+ version: 2,+ projectId,+ createdBy: "user",+ config: {},+ type: "TEXT",+ },+ ],+ });++ const res1 = await makeAPICall(+ "DELETE",+ `${baseURI}/${encodeURIComponent(name)}?version=1`,+ undefined,+ auth,+ );+ expect(res1.status).toBe(204);++ let remaining = await prisma.prompt.findMany({+ where: { projectId, name },+ });+ expect(remaining.length).toBe(1);++ const res2 = await makeAPICall(+ "DELETE",+ `${baseURI}/${encodeURIComponent(name)}?label=dev`,+ undefined,+ auth,+ );+ expect(res2.status).toBe(204);++ remaining = await prisma.prompt.findMany({ where: { projectId, name } });+ expect(remaining.length).toBe(0);+ });++ it("deletes a prompt with slashes in name (folder structure)", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ const name = "folder/subfolder/deletePrompt" + uuidv4();+ await prisma.prompt.create({+ data: {+ id: uuidv4(),+ name,+ prompt: "prompt in folder",+ labels: ["production"],+ version: 1,+ projectId,+ createdBy: "user",+ config: {},+ type: "TEXT",+ },+ });++ const res = await makeAPICall(+ "DELETE",+ `${baseURI}/${encodeURIComponent(name)}`,+ undefined,+ auth,+ );+ expect(res.status).toBe(204);++ const remaining = await prisma.prompt.findMany({+ where: { projectId, name },+ });+ expect(remaining.length).toBe(0);+ });++ it("returns 400 when deleting prompt with dependencies", async () => {+ const { projectId, auth } = await createOrgProjectAndApiKey();+ const childName = "childPrompt" + uuidv4();+ const parentName = "parentPrompt" + uuidv4();++ // Create child prompt+ await prisma.prompt.create({+ data: {+ id: uuidv4(),+ name: childName,+ prompt: "I am a child prompt",+ labels: ["production"],+ version: 1,+ projectId,+ createdBy: "user",+ config: {},+ type: "TEXT",+ },+ });++ // Create parent prompt that depends on child+ const parentPrompt = await prisma.prompt.create({+ data: {+ id: uuidv4(),+ name: parentName,+ prompt: `Parent with dependency: @@@langfusePrompt:name=${childName}|version=1@@@`,+ labels: ["production"],+ version: 1,+ projectId,+ createdBy: "user",+ config: {},+ type: "TEXT",+ },+ });++ // Create dependency relationship+ await prisma.promptDependency.create({+ data: {+ parentId: parentPrompt.id,+ childName: childName,+ childVersion: 1,+ projectId,+ },+ });++ // Try to delete child prompt (should fail because parent depends on it)+ const res = await makeAPICall(+ "DELETE",+ `${baseURI}/${encodeURIComponent(childName)}`,+ undefined,+ auth,+ );++ expect(res.status).toBe(400);+ expect(res.body).toHaveProperty("error");+ // @ts-expect-error+ expect(res.body.message).toContain("depending on");+ // @ts-expect-error+ expect(res.body.message).toContain(parentName);++ // Verify child was NOT deleted+ const remaining = await prisma.prompt.findMany({+ where: { projectId, name: childName },+ });+ expect(remaining.length).toBe(1);+ });+ });+describe("Parsing prompt dependency tags", () => {it("should extract prompt dependency tags with version", () => {const content =diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex b9f2d4a721..1469a00676 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -222,6 +222,11 @@ export async function makeAPICall<T = IngestionAPIResponse>(};const response = await fetch(finalUrl, options);+ // Handle 204 No Content - no body to parse+ if (response.status === 204) {+ return { body: {} as T, status: response.status };+ }+// Clone the response before attempting to parse JSONconst clonedResponse = response.clone();diff --git a/web/src/features/prompts/server/actions/deletePrompt.ts b/web/src/features/prompts/server/actions/deletePrompt.tsnew file mode 100644index 0000000000..4b5ad0f29d--- /dev/null+++ b/web/src/features/prompts/server/actions/deletePrompt.ts@@ -0,0 +1,93 @@+import { InvalidRequestError, LangfuseNotFoundError } from "@langfuse/shared";+import { prisma, type Prompt } from "@langfuse/shared/src/db";+import { PromptService, redis, logger } from "@langfuse/shared/src/server";++export type DeletePromptParams = {+ promptName: string;+ projectId: string;+ version?: number | null;+ label?: string;+ prompts?: Prompt[]; // Optional: if already fetched, avoid duplicate query+};++export const deletePrompt = async (params: DeletePromptParams) => {+ const {+ promptName,+ projectId,+ version,+ label,+ prompts: providedPrompts,+ } = params;++ if (version && label) {+ throw new InvalidRequestError("Cannot specify both version and label");+ }++ let prompts = providedPrompts;+ if (!prompts) {+ const where = {+ projectId,+ name: promptName,+ ...(version ? { version } : {}),+ ...(label ? { labels: { has: label } } : {}),+ };++ prompts = await prisma.prompt.findMany({ where });+ }++ if (prompts.length === 0) {+ throw new LangfuseNotFoundError("Prompt not found");+ }++ // Check if other prompts depend on the prompt(s) being deleted+ const dependents = await prisma.$queryRaw<+ {+ parent_name: string;+ parent_version: number;+ child_version: number;+ child_label: string;+ }[]+ >`+ SELECT+ p."name" AS "parent_name",+ p."version" AS "parent_version",+ pd."child_version" AS "child_version",+ pd."child_label" AS "child_label"+ FROM+ prompt_dependencies pd+ INNER JOIN prompts p ON p.id = pd.parent_id+ WHERE+ p.project_id = ${projectId}+ AND pd.project_id = ${projectId}+ AND pd.child_name = ${promptName}+ `;++ if (dependents.length > 0) {+ const dependencyMessages = dependents+ .map(+ (d) =>+ `${d.parent_name} v${d.parent_version} depends on ${promptName} ${d.child_version ? `v${d.child_version}` : d.child_label}`,+ )+ .join("\n");++ throw new InvalidRequestError(+ `Other prompts are depending on prompt versions you are trying to delete:\n\n${dependencyMessages}\n\nPlease delete the dependent prompts first.`,+ );+ }++ const promptService = new PromptService(prisma, redis);++ try {+ await promptService.lockCache({ projectId, promptName });+ await promptService.invalidateCache({ projectId, promptName });++ await prisma.prompt.deleteMany({+ where: { projectId, id: { in: prompts.map((p) => p.id) } },+ });+ } catch (err) {+ logger.error("Failed to delete prompt", err);+ throw err;+ } finally {+ await promptService.unlockCache({ projectId, promptName });+ }+};diff --git a/web/src/features/prompts/server/handlers/promptNameHandler.ts b/web/src/features/prompts/server/handlers/promptNameHandler.tsindex 732aaba107..2a0364c27a 100644--- a/web/src/features/prompts/server/handlers/promptNameHandler.ts+++ b/web/src/features/prompts/server/handlers/promptNameHandler.ts@@ -1,6 +1,7 @@import type { NextApiRequest, NextApiResponse } from "next";import { getPromptByName } from "@/src/features/prompts/server/actions/getPromptByName";+import { deletePrompt } from "@/src/features/prompts/server/actions/deletePrompt";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { authorizePromptRequestOrThrow } from "../utils/authorizePromptRequest";import {@@ -9,6 +10,8 @@ import {PRODUCTION_LABEL,} from "@langfuse/shared";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { prisma } from "@langfuse/shared/src/db";const getPromptNameHandler = async (req: NextApiRequest,@@ -46,9 +49,62 @@ const getPromptNameHandler = async (throw new LangfuseNotFoundError(errorMessage);}- return res.status(200).json(prompt);+ res.status(200).json(prompt);+};++const deletePromptNameHandler = async (+ req: NextApiRequest,+ res: NextApiResponse,+) => {+ const authCheck = await authorizePromptRequestOrThrow(req);++ const rateLimitCheck = await RateLimitService.getInstance().rateLimitRequest(+ authCheck.scope,+ "prompts",+ );++ if (rateLimitCheck?.isRateLimited()) {+ return rateLimitCheck.sendRestResponseIfLimited(res);+ }++ const { promptName, version, label } = GetPromptByNameSchema.parse(req.query);++ // Fetch prompts for audit logging+ const where = {+ projectId: authCheck.scope.projectId,+ name: promptName,+ ...(version ? { version } : {}),+ ...(label ? { labels: { has: label } } : {}),+ };++ const prompts = await prisma.prompt.findMany({ where });++ // Audit log before deletion+ for (const prompt of prompts) {+ await auditLog({+ action: "delete",+ resourceType: "prompt",+ resourceId: prompt.id,+ projectId: authCheck.scope.projectId,+ orgId: authCheck.scope.orgId,+ apiKeyId: authCheck.scope.apiKeyId,+ before: prompt,+ });+ }++ // Delete prompts (pass fetched prompts to avoid duplicate query)+ await deletePrompt({+ promptName,+ projectId: authCheck.scope.projectId,+ version,+ label,+ prompts, // Pass prompts to avoid duplicate query+ });++ res.status(204).end();};export const promptNameHandler = withMiddlewares({GET: getPromptNameHandler,+ DELETE: deletePromptNameHandler,});