Skip to content

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

feat: update prompt versions (#5106)

Max Deichmanne2015bc52b67
diff --git a/fern/apis/server/definition/prompt-version.yml b/fern/apis/server/definition/prompt-version.yml
new file mode 100644
index 0000000000..3f3fd9c110
--- /dev/null
+++ b/fern/apis/server/definition/prompt-version.yml
@@ -0,0 +1,27 @@
+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json
+imports:
+ prompts: ./prompts.yml
+ pagination: ./utils/pagination.yml
+service:
+ auth: true
+ base-path: /api/public/v2
+ endpoints:
+ update:
+ docs: Update labels for a specific prompt version
+ method: PATCH
+ path: /prompts/{promptName}/version/{version}
+ path-parameters:
+ promptName:
+ type: string
+ docs: The name of the prompt
+ version:
+ type: integer
+ docs: Version of the prompt to update
+ request:
+ name: UpdatePromptRequest
+ body:
+ properties:
+ newLabels:
+ type: list<string>
+ docs: New labels for the prompt version. Labels are unique across versions. The "latest" label is reserved and managed by Langfuse.
+ response: prompts.Prompt
diff --git a/fern/apis/server/definition/prompts.yml b/fern/apis/server/definition/prompts.yml
index bba38337df..c28d015336 100644
--- a/fern/apis/server/definition/prompts.yml
+++ b/fern/apis/server/definition/prompts.yml
@@ -102,7 +102,6 @@ types:
tags:
type: optional<list<string>>
docs: List of tags to apply to all versions of this prompt.
-
Prompt:
union:
chat: ChatPrompt
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 9dc80a1c91..bb6c7fad2a 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -1426,6 +1426,76 @@ paths:
schema: {}
security:
- BasicAuth: []
+ /api/public/v2/prompts/{promptName}/version/{version}:
+ patch:
+ description: Update labels for a specific prompt version
+ operationId: promptVersion_update
+ tags:
+ - PromptVersion
+ parameters:
+ - name: promptName
+ in: path
+ description: The name of the prompt
+ required: true
+ schema:
+ type: string
+ - name: version
+ in: path
+ description: Version of the prompt to update
+ required: true
+ schema:
+ type: integer
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Prompt'
+ '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: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ newLabels:
+ type: array
+ items:
+ type: string
+ description: >-
+ New labels for the prompt version. Labels are unique across
+ versions. The "latest" label is reserved and managed by
+ Langfuse.
+ required:
+ - newLabels
/api/public/v2/prompts/{promptName}:
get:
description: Get a prompt
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index ee5086fa44..a922b295ed 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -1057,6 +1057,61 @@
}
]
},
+ {
+ "_type": "container",
+ "description": null,
+ "name": "Prompt Version",
+ "item": [
+ {
+ "_type": "endpoint",
+ "name": "Update",
+ "request": {
+ "description": "Update labels for a specific prompt version",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/v2/prompts/:promptName/version/:version",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "v2",
+ "prompts",
+ ":promptName",
+ "version",
+ ":version"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "promptName",
+ "value": "",
+ "description": "The name of the prompt"
+ },
+ {
+ "key": "version",
+ "value": "",
+ "description": "Version of the prompt to update"
+ }
+ ]
+ },
+ "header": [],
+ "method": "PATCH",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"newLabels\": [\n \"example\"\n ]\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
+ }
+ ]
+ },
{
"_type": "container",
"description": null,
diff --git a/web/src/__tests__/prompts.v2.servertest.ts b/web/src/__tests__/prompts.v2.servertest.ts
index af9c9bf452..a00192b34b 100644
--- a/web/src/__tests__/prompts.v2.servertest.ts
+++ b/web/src/__tests__/prompts.v2.servertest.ts
@@ -13,7 +13,10 @@ import {
import { nanoid } from "ai";
import { type PromptsMetaResponse } from "@/src/features/prompts/server/actions/getPromptsMeta";
-import { getObservationById } from "@langfuse/shared/src/server";
+import {
+ createOrgProjectAndApiKey,
+ getObservationById,
+} from "@langfuse/shared/src/server";
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
const baseURI = "/api/public/v2/prompts";
@@ -1113,6 +1116,151 @@ describe("/api/public/v2/prompts API Endpoint", () => {
});
});
+describe("PATCH api/public/v2/prompts/[promptName]/version/[version]", () => {
+ it("should update the labels of a prompt", async () => {
+ const { projectId: newProjectId, auth: newAuth } =
+ await createOrgProjectAndApiKey();
+
+ const originalPrompt = await prisma.prompt.create({
+ data: {
+ name: "prompt-1",
+ projectId: newProjectId,
+ version: 1,
+ labels: ["production"],
+ createdBy: "user-test",
+ prompt: "prompt-1",
+ },
+ });
+
+ const response = await makeAPICall(
+ "PATCH",
+ `${baseURI}/prompt-1/version/1`,
+ {
+ newLabels: ["new-label"],
+ },
+ newAuth,
+ );
+
+ expect(response.status).toBe(200);
+
+ const updatedPrompt = await prisma.prompt.findUnique({
+ where: {
+ id: originalPrompt.id,
+ },
+ });
+ expect(updatedPrompt?.labels).toContain("production");
+ expect(updatedPrompt?.labels).toContain("new-label");
+ expect(updatedPrompt?.labels).toHaveLength(2);
+ });
+
+ it("should remove label from previous version when adding to new version", async () => {
+ const { projectId: newProjectId, auth: newAuth } =
+ await createOrgProjectAndApiKey();
+
+ // Create version 1 with "production" label
+ await prisma.prompt.create({
+ data: {
+ name: "prompt-1",
+ projectId: newProjectId,
+ version: 1,
+ labels: ["production"],
+ createdBy: "user-test",
+ prompt: "prompt-1",
+ },
+ });
+
+ // Create version 2 initially without the label
+ await prisma.prompt.create({
+ data: {
+ name: "prompt-1",
+ projectId: newProjectId,
+ version: 2,
+ labels: [],
+ createdBy: "user-test",
+ prompt: "prompt-1",
+ },
+ });
+
+ // Add "production" label to version 2
+ const response = await makeAPICall(
+ "PATCH",
+ `${baseURI}/prompt-1/version/2`,
+ {
+ newLabels: ["production"],
+ },
+ newAuth,
+ );
+
+ expect(response.status).toBe(200);
+ const responseBody = response.body as unknown as Prompt;
+ expect(responseBody.labels).toEqual(["production"]);
+
+ // Check version 2 got the label
+ const promptV2 = await prisma.prompt.findFirst({
+ where: {
+ projectId: newProjectId,
+ name: "prompt-1",
+ version: 2,
+ },
+ });
+ expect(promptV2?.labels).toEqual(["production"]);
+
+ // Check version 1 had the label removed
+ const promptV1 = await prisma.prompt.findFirst({
+ where: {
+ projectId: newProjectId,
+ name: "prompt-1",
+ version: 1,
+ },
+ });
+ expect(promptV1?.labels).toEqual([]);
+ });
+
+ it("trying to set 'latest' label results in 400 error", async () => {
+ const { projectId: newProjectId, auth: newAuth } =
+ await createOrgProjectAndApiKey();
+ // Create initial prompt version
+ await prisma.prompt.create({
+ data: {
+ name: "prompt-1",
+ projectId: newProjectId,
+ version: 1,
+ labels: [],
+ createdBy: "user-test",
+ prompt: "prompt-1",
+ },
+ });
+
+ // Try to set "latest" label
+ const response = await makeAPICall(
+ "PATCH",
+ `${baseURI}/prompt-1/version/1`,
+ {
+ newLabels: ["latest"],
+ },
+ newAuth,
+ );
+
+ expect(response.status).toBe(400);
+ });
+
+ it("updating non existing prompt results in 404", async () => {
+ const { auth: newAuth } = await createOrgProjectAndApiKey();
+
+ // Try to update non-existing prompt
+ const response = await makeAPICall(
+ "PATCH",
+ `${baseURI}/non-existing-prompt/version/1`,
+ {
+ newLabels: ["production"],
+ },
+ newAuth,
+ );
+
+ expect(response.status).toBe(404);
+ });
+});
+
const isPrompt = (x: unknown): x is Prompt => {
if (typeof x !== "object" || x === null) return false;
const prompt = x as Prompt;
diff --git a/web/src/features/prompts/server/actions/updatePrompts.ts b/web/src/features/prompts/server/actions/updatePrompts.ts
new file mode 100644
index 0000000000..5ddea318b7
--- /dev/null
+++ b/web/src/features/prompts/server/actions/updatePrompts.ts
@@ -0,0 +1,74 @@
+import { logger, PromptService } from "@langfuse/shared/src/server";
+import { removeLabelsFromPreviousPromptVersions } from "@/src/features/prompts/server/utils/updatePromptLabels";
+import { LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { redis } from "@langfuse/shared/src/server";
+
+export type UpdatePromptParams = {
+ promptName: string;
+ projectId: string;
+ promptVersion: number;
+ newLabels: string[];
+};
+
+export const updatePrompt = async (params: UpdatePromptParams) => {
+ const { promptName, projectId, promptVersion, newLabels } = params;
+
+ logger.info(
+ `Updating prompt ${promptName} in project ${projectId} version ${promptVersion} with labels ${newLabels}`,
+ );
+ const promptService = new PromptService(prisma, redis);
+ try {
+ await promptService.lockCache({ projectId, promptName: promptName });
+
+ const prompt = await promptService.getPrompt({
+ projectId,
+ promptName,
+ version: promptVersion,
+ label: undefined,
+ });
+
+ if (!prompt) {
+ throw new LangfuseNotFoundError(`Prompt not found: ${promptName}`);
+ }
+
+ const newLabelsSet = new Set([...newLabels, ...prompt.labels]);
+
+ logger.info(
+ `Setting labels for prompt: ${prompt.id}, ${prompt.name}, ${prompt.version}, ${JSON.stringify(
+ Array.from(newLabelsSet),
+ )}`,
+ );
+
+ const tx = [
+ ...(await removeLabelsFromPreviousPromptVersions({
+ prisma,
+ projectId,
+ promptName,
+ labelsToRemove: [...new Set(newLabels)],
+ })),
+ prisma.prompt.update({
+ where: {
+ id: prompt.id,
+ projectId,
+ },
+ data: {
+ labels: {
+ set: Array.from(newLabelsSet),
+ },
+ },
+ }),
+ ];
+
+ await promptService.invalidateCache({ projectId, promptName: promptName });
+
+ const res = await prisma.$transaction(tx);
+
+ await promptService.unlockCache({ projectId, promptName: promptName });
+
+ return res[res.length - 1];
+ } catch (e) {
+ await promptService.unlockCache({ projectId, promptName: promptName });
+ throw e;
+ }
+};
diff --git a/web/src/features/prompts/server/handlers/promptNameHandler.ts b/web/src/features/prompts/server/handlers/promptNameHandler.ts
index cc00b2478d..f2cbd176d5 100644
--- a/web/src/features/prompts/server/handlers/promptNameHandler.ts
+++ b/web/src/features/prompts/server/handlers/promptNameHandler.ts
@@ -48,4 +48,6 @@ const getPromptNameHandler = async (
return res.status(200).json(prompt);
};
-export const promptNameHandler = withMiddlewares({ GET: getPromptNameHandler });
+export const promptNameHandler = withMiddlewares({
+ GET: getPromptNameHandler,
+});
diff --git a/web/src/features/prompts/server/handlers/promptVersionHandler.ts b/web/src/features/prompts/server/handlers/promptVersionHandler.ts
new file mode 100644
index 0000000000..d59eb7f9f3
--- /dev/null
+++ b/web/src/features/prompts/server/handlers/promptVersionHandler.ts
@@ -0,0 +1,46 @@
+import { logger } from "@langfuse/shared/src/server";
+import { z } from "zod";
+
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";
+import { updatePrompt } from "@/src/features/prompts/server/actions/updatePrompts";
+import { LangfuseNotFoundError } from "@langfuse/shared";
+
+const UpdatePromptBodySchema = z.object({
+ newLabels: z
+ .array(z.string())
+ .refine((labels) => !labels.includes("latest"), {
+ message: "Label 'latest' is always assigned to the latest prompt version",
+ }),
+});
+
+export const promptVersionHandler = withMiddlewares({
+ PATCH: createAuthedAPIRoute({
+ name: "Update Prompt",
+ bodySchema: UpdatePromptBodySchema,
+ responseSchema: z.any(),
+ fn: async ({ body, res, req, auth }) => {
+ try {
+ const { newLabels } = UpdatePromptBodySchema.parse(body);
+ const { promptName, promptVersion } = req.query;
+
+ const prompt = await updatePrompt({
+ promptName: promptName as string,
+ projectId: auth.scope.projectId,
+ promptVersion: Number(promptVersion),
+ newLabels,
+ });
+
+ logger.info(`Prompt updated ${JSON.stringify(prompt)}`);
+
+ return res.status(200).json(prompt);
+ } catch (e) {
+ logger.error(e);
+ if (e instanceof LangfuseNotFoundError) {
+ return res.status(404).json({ message: e.message });
+ }
+ return res.status(500).json({ message: "Internal server error" });
+ }
+ },
+ }),
+});
diff --git a/web/src/pages/api/public/v2/prompts/[promptName].ts b/web/src/pages/api/public/v2/prompts/[promptName]/index.ts
similarity index 100%
rename from web/src/pages/api/public/v2/prompts/[promptName].ts
rename to web/src/pages/api/public/v2/prompts/[promptName]/index.ts
diff --git a/web/src/pages/api/public/v2/prompts/[promptName]/version/[promptVersion].ts b/web/src/pages/api/public/v2/prompts/[promptName]/version/[promptVersion].ts
new file mode 100644
index 0000000000..281207c17f
--- /dev/null
+++ b/web/src/pages/api/public/v2/prompts/[promptName]/version/[promptVersion].ts
@@ -0,0 +1 @@
+export { promptVersionHandler as default } from "@/src/features/prompts/server/handlers/promptVersionHandler";