Skip to content

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

feat(prompts): support in UI prompt duplication (#5110)

marliessophie484af104634c
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 1b1216dd02..f1fb8a7ebf 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -57,6 +57,8 @@ const events = {
"apply_labels",
"version_delete_open",
"version_delete_submit",
+ "duplicate_button_click",
+ "duplicate_form_submit",
],
session_detail: ["publish_button_click"],
eval_config: [
diff --git a/web/src/features/prompts/components/NewPromptForm/index.tsx b/web/src/features/prompts/components/NewPromptForm/index.tsx
index 3aae42d83f..5699f3f89b 100644
--- a/web/src/features/prompts/components/NewPromptForm/index.tsx
+++ b/web/src/features/prompts/components/NewPromptForm/index.tsx
@@ -50,6 +50,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePos
import usePlaygroundCache from "@/src/ee/features/playground/page/hooks/usePlaygroundCache";
import { useQueryParam } from "use-query-params";
import { Switch } from "@/src/components/ui/switch";
+import { usePromptNameValidation } from "@/src/features/prompts/hooks/usePromptNameValidation";
type NewPromptFormProps = {
initialPrompt?: Prompt | null;
@@ -186,24 +187,11 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
}
}, [playgroundCache, initialPrompt, form, shouldLoadPlaygroundCache]);
- useEffect(() => {
- const isNewPrompt = !allPrompts
- ?.map((prompt) => prompt.value)
- .includes(currentName);
-
- if (!isNewPrompt) {
- form.setError("name", { message: "Prompt name already exist." });
- } else if (currentName === "new") {
- form.setError("name", { message: "Prompt name cannot be 'new'" });
- } else if (currentName && !/^[a-zA-Z0-9_\-.]+$/.test(currentName)) {
- form.setError("name", {
- message:
- "Name must be alphanumeric with optional underscores, hyphens, or periods",
- });
- } else {
- form.clearErrors("name");
- }
- }, [currentName, allPrompts, form]);
+ usePromptNameValidation({
+ currentName,
+ allPrompts,
+ form,
+ });
return (
<Form {...form}>
diff --git a/web/src/features/prompts/components/duplicate-prompt.tsx b/web/src/features/prompts/components/duplicate-prompt.tsx
new file mode 100644
index 0000000000..86279998b3
--- /dev/null
+++ b/web/src/features/prompts/components/duplicate-prompt.tsx
@@ -0,0 +1,233 @@
+import { useRouter } from "next/router";
+import { Button } from "@/src/components/ui/button";
+import { api } from "@/src/utils/api";
+import { Copy } from "lucide-react";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import { ActionButton } from "@/src/components/ActionButton";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useEntitlementLimit } from "@/src/features/entitlements/hooks";
+import { useState } from "react";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Input } from "@/src/components/ui/input";
+import { RadioGroup, RadioGroupItem } from "@/src/components/ui/radio-group";
+import { usePromptNameValidation } from "@/src/features/prompts/hooks/usePromptNameValidation";
+
+enum CopySettings {
+ SINGLE_VERSION = "single_version",
+ ALL_VERSIONS = "all_versions",
+}
+
+const formSchema = z.object({
+ name: z.string().min(1, "Name is required"),
+ isCopySingleVersion: z.nativeEnum(CopySettings),
+});
+
+const DuplicatePromptForm: React.FC<{
+ projectId: string;
+ promptId: string;
+ promptName: string;
+ promptVersion: number;
+ onFormSuccess: () => void;
+}> = ({ projectId, promptId, promptName, promptVersion, onFormSuccess }) => {
+ const capture = usePostHogClientCapture();
+ const router = useRouter();
+ const form = useForm<z.infer<typeof formSchema>>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ name: promptName,
+ isCopySingleVersion: CopySettings.SINGLE_VERSION,
+ },
+ });
+
+ const currentName = form.watch("name");
+
+ const utils = api.useUtils();
+ const duplicatePrompt = api.prompts.duplicatePrompt.useMutation({
+ onSuccess: ({ name }) => {
+ utils.prompts.invalidate();
+ void router.push(
+ `/project/${projectId}/prompts/${encodeURIComponent(name)}`,
+ );
+ },
+ });
+
+ function onSubmit(values: z.infer<typeof formSchema>) {
+ capture("prompt_detail:duplicate_form_submit");
+ duplicatePrompt
+ .mutateAsync({
+ ...values,
+ projectId: projectId,
+ promptId: promptId,
+ isSingleVersion:
+ values.isCopySingleVersion === CopySettings.SINGLE_VERSION,
+ })
+ .then(() => {
+ onFormSuccess();
+ form.reset();
+ })
+ .catch((error: Error) => {
+ console.error(error);
+ });
+ }
+
+ const allPrompts = api.prompts.filterOptions.useQuery(
+ {
+ projectId: projectId,
+ },
+ {
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ staleTime: Infinity,
+ },
+ ).data?.name;
+
+ usePromptNameValidation({
+ currentName,
+ allPrompts,
+ form,
+ });
+
+ return (
+ <Form {...form}>
+ <form
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="mt-4 flex h-full flex-1 flex-col gap-4"
+ >
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem className="flex flex-col gap-2">
+ <FormLabel>Name</FormLabel>
+ <FormControl>
+ <Input {...field} type="text" />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="isCopySingleVersion"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Settings</FormLabel>
+ <FormControl>
+ <RadioGroup
+ {...field}
+ onValueChange={field.onChange}
+ defaultValue={field.value}
+ className="flex flex-col space-y-1"
+ >
+ <FormItem className="flex items-center space-x-3 space-y-0">
+ <FormControl>
+ <RadioGroupItem value={CopySettings.SINGLE_VERSION} />
+ </FormControl>
+ <FormLabel className="font-normal">
+ Copy only version {promptVersion}
+ </FormLabel>
+ </FormItem>
+ <FormItem className="flex items-center space-x-3 space-y-0">
+ <FormControl>
+ <RadioGroupItem value={CopySettings.ALL_VERSIONS} />
+ </FormControl>
+ <FormLabel className="font-normal">
+ Copy all prompt versions and labels
+ </FormLabel>
+ </FormItem>
+ </RadioGroup>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <Button
+ type="submit"
+ loading={duplicatePrompt.isLoading}
+ className="mb-4 mt-auto w-full"
+ >
+ Submit
+ </Button>
+ </form>
+ </Form>
+ );
+};
+
+export const DuplicatePromptButton: React.FC<{
+ projectId: string;
+ promptId: string;
+ promptName: string;
+ promptVersion: number;
+}> = ({ projectId, promptId, promptName, promptVersion }) => {
+ const [open, setOpen] = useState(false);
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "prompts:CUD",
+ });
+ const promptLimit = useEntitlementLimit("prompt-management-count-prompts");
+ const capture = usePostHogClientCapture();
+
+ const allPromptNames = api.prompts.allNames.useQuery(
+ {
+ projectId,
+ },
+ {
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ enabled: hasAccess,
+ },
+ );
+
+ return (
+ <Dialog open={hasAccess && open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <ActionButton
+ icon={<Copy className="mr-1 h-4 w-4" aria-hidden="true" />}
+ hasAccess={hasAccess}
+ variant="secondary"
+ limit={promptLimit}
+ title="Duplicate prompt"
+ limitValue={allPromptNames.data?.length ?? undefined}
+ onClick={() => {
+ capture("prompt_detail:duplicate_button_click");
+ }}
+ >
+ Duplicate
+ </ActionButton>
+ </DialogTrigger>
+ <DialogContent className="max-h-[90vh] min-h-0">
+ <DialogHeader>
+ <DialogTitle>Duplicate prompt</DialogTitle>
+ </DialogHeader>
+ <DuplicatePromptForm
+ projectId={projectId}
+ promptId={promptId}
+ promptName={promptName}
+ promptVersion={promptVersion}
+ onFormSuccess={() => setOpen(false)}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsx
index 88bc375d46..1ae82a6943 100644
--- a/web/src/features/prompts/components/prompt-detail.tsx
+++ b/web/src/features/prompts/components/prompt-detail.tsx
@@ -39,6 +39,7 @@ import { CreateExperimentsForm } from "@/src/ee/features/experiments/components/
import { useState } from "react";
import { useHasEntitlement } from "@/src/features/entitlements/hooks";
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { DuplicatePromptButton } from "@/src/features/prompts/components/duplicate-prompt";
export const PromptDetail = () => {
const projectId = useProjectIdFromURL();
@@ -224,6 +225,14 @@ export const PromptDetail = () => {
</div>
</Button>
)}
+ {projectId && (
+ <DuplicatePromptButton
+ promptId={prompt.id}
+ projectId={projectId}
+ promptName={prompt.name}
+ promptVersion={prompt.version}
+ />
+ )}
<DetailPageNav
key="nav"
currentId={promptName}
diff --git a/web/src/features/prompts/hooks/usePromptNameValidation.tsx b/web/src/features/prompts/hooks/usePromptNameValidation.tsx
new file mode 100644
index 0000000000..affaf07386
--- /dev/null
+++ b/web/src/features/prompts/hooks/usePromptNameValidation.tsx
@@ -0,0 +1,35 @@
+import { useEffect } from "react";
+import { type UseFormReturn } from "react-hook-form";
+
+interface UsePromptNameValidationProps {
+ currentName: string | undefined;
+ allPrompts: { value: string }[] | undefined;
+ form: UseFormReturn<any>;
+}
+
+export const usePromptNameValidation = ({
+ currentName,
+ allPrompts,
+ form,
+}: UsePromptNameValidationProps) => {
+ useEffect(() => {
+ if (!currentName) return;
+
+ const isNewPrompt = !allPrompts
+ ?.map((prompt) => prompt.value)
+ .includes(currentName);
+
+ if (!isNewPrompt) {
+ form.setError("name", { message: "Prompt name already exist." });
+ } else if (currentName === "new") {
+ form.setError("name", { message: "Prompt name cannot be 'new'" });
+ } else if (!/^[a-zA-Z0-9_\-.]+$/.test(currentName)) {
+ form.setError("name", {
+ message:
+ "Name must be alphanumeric with optional underscores, hyphens, or periods",
+ });
+ } else {
+ form.clearErrors("name");
+ }
+ }, [currentName, allPrompts, form]);
+};
diff --git a/web/src/features/prompts/server/actions/createPrompt.ts b/web/src/features/prompts/server/actions/createPrompt.ts
index 6fba4cee46..12fbd7b294 100644
--- a/web/src/features/prompts/server/actions/createPrompt.ts
+++ b/web/src/features/prompts/server/actions/createPrompt.ts
@@ -8,13 +8,26 @@ import { type PrismaClient } from "@langfuse/shared/src/db";
import { LATEST_PROMPT_LABEL } from "@/src/features/prompts/constants";
import { removeLabelsFromPreviousPromptVersions } from "@/src/features/prompts/server/utils/updatePromptLabels";
import { updatePromptTagsOnAllVersions } from "@/src/features/prompts/server/utils/updatePromptTags";
-import { PromptService, redis } from "@langfuse/shared/src/server";
+import {
+ PromptContentSchema,
+ PromptService,
+ redis,
+} from "@langfuse/shared/src/server";
export type CreatePromptParams = CreatePromptTRPCType & {
createdBy: string;
prisma: PrismaClient;
};
+type DuplicatePromptParams = {
+ projectId: string;
+ promptId: string;
+ name: string;
+ isSingleVersion: boolean;
+ createdBy: string;
+ prisma: PrismaClient;
+};
+
export const createPrompt = async ({
projectId,
name,
@@ -96,3 +109,78 @@ export const createPrompt = async ({
return createdPrompt;
};
+
+export const duplicatePrompt = async ({
+ projectId,
+ promptId,
+ name,
+ isSingleVersion,
+ createdBy,
+ prisma,
+}: DuplicatePromptParams) => {
+ // validate that name is unique in project, uniqueness constraint too permissive as it includes version
+ const promptNameExists = await prisma.prompt.findFirst({
+ where: {
+ projectId,
+ name,
+ },
+ });
+
+ if (promptNameExists) {
+ throw new InvalidRequestError(
+ `Prompt name ${name} already exists in project ${projectId}`,
+ );
+ }
+
+ const existingPrompt = await prisma.prompt.findUnique({
+ where: {
+ id: promptId,
+ projectId: projectId,
+ },
+ });
+
+ if (!existingPrompt) {
+ throw new Error(`Existing prompt not found: ${promptId}`);
+ }
+
+ // if defined as single version, duplicate current prompt as new prompt v1
+ // else duplicate the entire prompt, should be all or nothing operation.
+ const promptsDb = await prisma.prompt.findMany({
+ where: {
+ projectId: projectId,
+ name: existingPrompt.name,
+ version: isSingleVersion ? existingPrompt.version : undefined,
+ },
+ });
+
+ // prepare createMany prompt records
+ const promptsToCreate = promptsDb.map((prompt) => ({
+ name,
+ version: isSingleVersion ? 1 : prompt.version,
+ labels: isSingleVersion
+ ? [...new Set([LATEST_PROMPT_LABEL, ...prompt.labels])]
+ : prompt.labels,
+ type: prompt.type,
+ prompt: PromptContentSchema.parse(prompt.prompt),
+ config: jsonSchema.parse(prompt.config),
+ tags: prompt.tags,
+ projectId,
+ createdBy,
+ }));
+
+ // Create all prompts in a single operation
+ const result = await prisma.prompt.createMany({
+ data: promptsToCreate,
+ });
+
+ // If you need the created prompt, fetch it separately since createMany doesn't return created records
+ const createdPrompt = await prisma.prompt.findFirst({
+ where: {
+ name,
+ projectId,
+ version: isSingleVersion ? 1 : result.count,
+ },
+ });
+
+ return createdPrompt;
+};
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index c9e0dc08fa..5e58fc5300 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -11,7 +11,7 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { type Prompt, Prisma } from "@langfuse/shared/src/db";
-import { createPrompt } from "../actions/createPrompt";
+import { createPrompt, duplicatePrompt } from "../actions/createPrompt";
import { promptsTableCols } from "@/src/server/api/definitions/promptsTable";
import { optionalPaginationZod, paginationZod } from "@langfuse/shared";
import { orderBy, singleFilter } from "@langfuse/shared";
@@ -172,6 +172,48 @@ export const promptRouter = createTRPCRouter({
throw e;
}
}),
+ duplicatePrompt: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ promptId: z.string(),
+ name: z.string(),
+ isSingleVersion: z.boolean(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "prompts:CUD",
+ });
+
+ const prompt = await duplicatePrompt({
+ projectId: input.projectId,
+ promptId: input.promptId,
+ name: input.name,
+ isSingleVersion: input.isSingleVersion,
+ createdBy: ctx.session.user.id,
+ prisma: ctx.prisma,
+ });
+
+ if (!prompt) {
+ throw new Error(`Failed to duplicate prompt: ${input.promptId}`);
+ }
+
+ await auditLog(
+ {
+ session: ctx.session,
+ resourceType: "prompt",
+ resourceId: prompt.id,
+ action: "create",
+ after: prompt,
+ },
+ ctx.prisma,
+ );
+
+ return prompt;
+ }),
filterOptions: protectedProjectProcedure
.input(z.object({ projectId: z.string() }))
.query(async ({ input, ctx }) => {