Skip to content

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

feat(prompts): add bulk export and import for prompts (#13774)

rkdhandab11fbfe568ee
diff --git a/web/src/__tests__/server/prompts-trpc.servertest.ts b/web/src/__tests__/server/prompts-trpc.servertest.ts
index e62f4f0c88..4df48a3ace 100644
--- a/web/src/__tests__/server/prompts-trpc.servertest.ts
+++ b/web/src/__tests__/server/prompts-trpc.servertest.ts
@@ -2,10 +2,15 @@ import { disconnectQueues } from "@/src/__tests__/test-utils";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import { prisma } from "@langfuse/shared/src/db";
-import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import {
+ createOrgProjectAndApiKey,
+ EntityChangeQueue,
+} from "@langfuse/shared/src/server";
+import { PromptType } from "@langfuse/shared";
import type { Session } from "next-auth";
import { v4 } from "uuid";
import waitForExpect from "wait-for-expect";
+import { entitlementAccess } from "@/src/features/entitlements/constants/entitlements";
function createCaller({
projectId,
@@ -13,12 +18,14 @@ function createCaller({
projectName = "Test project",
orgName = "Test organization",
admin = true,
+ projectRole = "ADMIN",
}: {
projectId: string;
orgId: string;
projectName?: string;
orgName?: string;
admin?: boolean;
+ projectRole?: "ADMIN" | "MEMBER";
}) {
const session: Session = {
expires: "1",
@@ -39,7 +46,7 @@ function createCaller({
projects: [
{
id: projectId,
- role: "ADMIN",
+ role: projectRole,
retentionDays: 30,
deletedAt: null,
hasTraces: false,
@@ -132,6 +139,223 @@ describe("prompts trpc", () => {
);
});
+ describe("prompts.importBulk", () => {
+ it("enforces the prompt count limit for new prompt names", async () => {
+ const { project, org } = await createOrgProjectAndApiKey();
+ const existingPromptName = `existing-${v4()}`;
+ await prisma.prompt.create({
+ data: {
+ projectId: project.id,
+ name: existingPromptName,
+ version: 1,
+ type: "text",
+ prompt: "Version 1",
+ createdBy: "API",
+ labels: ["latest"],
+ },
+ });
+ const { caller } = createCaller({
+ projectId: project.id,
+ orgId: org.id,
+ projectName: project.name,
+ orgName: org.name,
+ admin: false,
+ });
+ const previousLimit =
+ entitlementAccess["cloud:hobby"].entitlementLimits[
+ "prompt-management-count-prompts"
+ ];
+ entitlementAccess["cloud:hobby"].entitlementLimits[
+ "prompt-management-count-prompts"
+ ] = 1;
+
+ try {
+ const existingPromptResult = await caller.prompts.importBulk({
+ projectId: project.id,
+ prompts: [{ name: existingPromptName, prompt: "Version 2" }],
+ });
+ expect(existingPromptResult.results).toEqual([
+ { name: existingPromptName, success: true },
+ ]);
+
+ const newPromptName = `new-${v4()}`;
+ await expect(
+ caller.prompts.importBulk({
+ projectId: project.id,
+ prompts: [{ name: newPromptName, prompt: "Version 1" }],
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ await expect(
+ prisma.prompt.findFirst({
+ where: { projectId: project.id, name: newPromptName },
+ }),
+ ).resolves.toBeNull();
+ } finally {
+ entitlementAccess["cloud:hobby"].entitlementLimits[
+ "prompt-management-count-prompts"
+ ] = previousLimit;
+ }
+ });
+
+ it("rejects protected labels without protected-label access", async () => {
+ const { project, org } = await createOrgProjectAndApiKey();
+ const protectedLabel = `protected-${v4().slice(0, 8)}`;
+ await prisma.promptProtectedLabels.create({
+ data: { projectId: project.id, label: protectedLabel },
+ });
+ const { caller } = createCaller({
+ projectId: project.id,
+ orgId: org.id,
+ projectName: project.name,
+ orgName: org.name,
+ admin: false,
+ projectRole: "MEMBER",
+ });
+
+ await expect(
+ caller.prompts.importBulk({
+ projectId: project.id,
+ prompts: [
+ {
+ name: `protected-label-import-${v4()}`,
+ prompt: "Hello world",
+ labels: [protectedLabel],
+ },
+ ],
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ });
+
+ it.each([
+ {
+ caseName: "array content without a chat type",
+ prompt: { name: "invalid-text-prompt", prompt: [] },
+ },
+ {
+ caseName: "string content with a chat type",
+ prompt: {
+ name: "invalid-chat-prompt",
+ type: "chat",
+ prompt: "Hello world",
+ },
+ },
+ {
+ caseName: "a malformed chat message",
+ prompt: {
+ name: "invalid-chat-message",
+ type: "chat",
+ prompt: [{ role: "user" }],
+ },
+ },
+ ])("rejects $caseName", async ({ prompt }) => {
+ const { project, caller } = await prepare();
+ const input: unknown = {
+ projectId: project.id,
+ prompts: [prompt],
+ };
+
+ await expect(
+ caller.prompts.importBulk(
+ input as Parameters<typeof caller.prompts.importBulk>[0],
+ ),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ });
+
+ it("reports a committed item as successful when audit logging fails", async () => {
+ const { project, caller } = await prepare();
+ const promptName = `audit-failure-${v4()}`;
+ const auditLogCreateSpy = vi
+ .spyOn(prisma.auditLog, "create")
+ .mockRejectedValueOnce(new Error("audit log unavailable"));
+
+ try {
+ const result = await caller.prompts.importBulk({
+ projectId: project.id,
+ prompts: [{ name: promptName, prompt: "Hello world" }],
+ });
+
+ expect(result.results).toEqual([{ name: promptName, success: true }]);
+ await expect(
+ prisma.prompt.findUnique({
+ where: {
+ projectId_name_version: {
+ projectId: project.id,
+ name: promptName,
+ version: 1,
+ },
+ },
+ }),
+ ).resolves.not.toBeNull();
+ } finally {
+ auditLogCreateSpy.mockRestore();
+ }
+ });
+
+ it("reports a committed item as successful when event sourcing fails", async () => {
+ const { project, caller } = await prepare();
+ const promptName = `event-failure-${v4()}`;
+ const getQueueSpy = vi
+ .spyOn(EntityChangeQueue, "getInstance")
+ .mockReturnValue({
+ add: vi.fn().mockRejectedValue(new Error("queue unavailable")),
+ } as never);
+
+ try {
+ const result = await caller.prompts.importBulk({
+ projectId: project.id,
+ prompts: [{ name: promptName, prompt: "Hello world" }],
+ });
+
+ expect(result.results).toEqual([{ name: promptName, success: true }]);
+ await expect(
+ prisma.prompt.findUnique({
+ where: {
+ projectId_name_version: {
+ projectId: project.id,
+ name: promptName,
+ version: 1,
+ },
+ },
+ }),
+ ).resolves.not.toBeNull();
+ } finally {
+ getQueueSpy.mockRestore();
+ }
+ });
+
+ it("reports failures that happen before the prompt is committed", async () => {
+ const { project, caller } = await prepare();
+ const promptName = `type-mismatch-${v4()}`;
+ await caller.prompts.importBulk({
+ projectId: project.id,
+ prompts: [{ name: promptName, prompt: "Text prompt" }],
+ });
+
+ const result = await caller.prompts.importBulk({
+ projectId: project.id,
+ prompts: [
+ {
+ name: promptName,
+ type: PromptType.Chat,
+ prompt: [{ role: "user", content: "Chat prompt" }],
+ },
+ ],
+ });
+
+ expect(result.results).toEqual([
+ expect.objectContaining({
+ name: promptName,
+ success: false,
+ }),
+ ]);
+ await expect(
+ prisma.prompt.count({
+ where: { projectId: project.id, name: promptName },
+ }),
+ ).resolves.toBe(1);
+ });
+ });
+
describe("prompts.allVersions", () => {
it("returns comment counts for the requested prompt version page only", async () => {
const { project, caller } = await prepare();
diff --git a/web/src/components/design-system/Dropzone/Dropzone.tsx b/web/src/components/design-system/Dropzone/Dropzone.tsx
index 98bd17696f..ea1af8db83 100644
--- a/web/src/components/design-system/Dropzone/Dropzone.tsx
+++ b/web/src/components/design-system/Dropzone/Dropzone.tsx
@@ -26,7 +26,7 @@ export type DropzoneProps = {
onError: ((error: Error) => void) | undefined;
src: File[] | undefined;
maxFiles: number;
- maxSize: number;
+ maxSize: number | undefined;
onDrop: (acceptedFiles: File[]) => void;
variant: "compact" | "panel";
};
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index c2eec4a26c..95355ad9b1 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -123,6 +123,8 @@ export const events = {
"new_form_open",
"update_form_open",
"update_form_submit",
+ "bulk_export",
+ "bulk_import_submit",
],
prompt_detail: [
"test_in_playground_button_click",
diff --git a/web/src/features/prompts/components/ImportPromptsButtonDialogController.tsx b/web/src/features/prompts/components/ImportPromptsButtonDialogController.tsx
new file mode 100644
index 0000000000..09bbdfa95e
--- /dev/null
+++ b/web/src/features/prompts/components/ImportPromptsButtonDialogController.tsx
@@ -0,0 +1,269 @@
+import { type ReactNode, useState } from "react";
+import { CheckCircle, XCircle, Loader2 } from "lucide-react";
+import { Dropzone } from "@/src/components/design-system/Dropzone/Dropzone";
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/src/components/ui/dialog";
+import { api } from "@/src/utils/api";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { CreatePromptSchema } from "@langfuse/shared";
+import { z } from "zod";
+
+type ImportItem = z.infer<typeof CreatePromptSchema>;
+
+const IMPORT_MAX = 500;
+
+const importPayloadSchema = z
+ .array(CreatePromptSchema)
+ .min(1, "File contains an empty array.")
+ .max(
+ IMPORT_MAX,
+ `File contains more than ${IMPORT_MAX} prompts — maximum per import is ${IMPORT_MAX}. Split the file and import in batches.`,
+ );
+
+function validateImportPayload(raw: unknown): ImportItem[] {
+ if (!Array.isArray(raw)) {
+ throw new Error("File must contain a JSON array of prompts.");
+ }
+ const result = importPayloadSchema.safeParse(raw);
+ if (!result.success) {
+ const firstIssue = result.error.issues[0];
+ throw new Error(firstIssue?.message ?? "Invalid import payload.");
+ }
+ return result.data;
+}
+
+type ImportResult = {
+ name: string;
+ success: boolean;
+ error?: string;
+};
+
+type ImportState =
+ | { step: "idle" }
+ | { step: "parsed"; file: File; items: ImportItem[]; importError?: string }
+ | { step: "error"; file?: File; error: string }
+ | { step: "done"; results: ImportResult[] };
+
+const ImportPromptsDialogContent: React.FC<{
+ isImportPending: boolean;
+ onClose: () => void;
+ onImport: (items: ImportItem[]) => Promise<{ results: ImportResult[] }>;
+}> = ({ isImportPending, onClose, onImport }) => {
+ const capture = usePostHogClientCapture();
+ const [state, setState] = useState<ImportState>({ step: "idle" });
+
+ const handleFiles = (files: File[]) => {
+ const file = files[0];
+ if (!file) return;
+
+ setState({ step: "idle" });
+
+ const reader = new FileReader();
+ reader.onload = (event) => {
+ try {
+ const text = event.target?.result;
+ if (typeof text !== "string") throw new Error("Failed to read file.");
+ const raw = JSON.parse(text) as unknown;
+ const items = validateImportPayload(raw);
+ setState({ step: "parsed", file, items });
+ } catch (err) {
+ setState({
+ step: "error",
+ file,
+ error: err instanceof Error ? err.message : "Failed to parse file.",
+ });
+ }
+ };
+ reader.readAsText(file);
+ };
+
+ const handleImport = async () => {
+ if (state.step !== "parsed") return;
+ capture("prompts:bulk_import_submit", { count: state.items.length });
+ const parsedState = state;
+ setState({ ...parsedState, importError: undefined });
+
+ try {
+ const data = await onImport(parsedState.items);
+ setState({ step: "done", results: data.results });
+ } catch (error) {
+ setState({
+ ...parsedState,
+ importError:
+ error instanceof Error ? error.message : "Failed to import prompts.",
+ });
+ }
+ };
+
+ if (state.step === "done") {
+ const successCount = state.results.filter((r) => r.success).length;
+ const failCount = state.results.filter((r) => !r.success).length;
+
+ return (
+ <>
+ <DialogBody className="flex flex-col gap-4">
+ <div className="flex flex-col gap-2">
+ <p className="text-sm font-bold">
+ Import complete — {successCount} succeeded, {failCount} failed.
+ </p>
+ <div className="max-h-64 overflow-y-auto rounded-md border p-2 text-sm">
+ {state.results.map((r, index) => (
+ <div
+ key={`${r.name}-${index}`}
+ className="flex items-start gap-2 py-1"
+ >
+ {r.success ? (
+ <CheckCircle className="mt-0.5 h-4 w-4 shrink-0 text-green-500" />
+ ) : (
+ <XCircle className="text-destructive mt-0.5 h-4 w-4 shrink-0" />
+ )}
+ <span className="font-mono">{r.name}</span>
+ {r.error && (
+ <span className="text-muted-foreground ml-auto text-xs">
+ {r.error}
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ </DialogBody>
+
+ <DialogFooter>
+ <Button onClick={onClose} className="w-full">
+ Done
+ </Button>
+ </DialogFooter>
+ </>
+ );
+ }
+
+ const selectedFile =
+ state.step === "parsed" || state.step === "error" ? state.file : undefined;
+ const parsedItems = state.step === "parsed" ? state.items : null;
+ const error =
+ state.step === "error"
+ ? state.error
+ : state.step === "parsed"
+ ? state.importError
+ : undefined;
+
+ return (
+ <>
+ <DialogBody className="flex flex-col gap-4">
+ <p className="text-muted-foreground text-sm">
+ Upload a JSON file exported from Langfuse. Each prompt will be created
+ as a new version if the name already exists.
+ </p>
+ <p className="text-muted-foreground text-sm">
+ The production label is not imported. The newest imported version is
+ automatically labeled latest.
+ </p>
+ <Dropzone
+ accept={{ "application/json": [".json"] }}
+ isDisabled={isImportPending}
+ maxFiles={1}
+ maxSize={undefined}
+ minSize={undefined}
+ onDrop={handleFiles}
+ onError={(error) => setState({ step: "error", error: error.message })}
+ src={selectedFile ? [selectedFile] : undefined}
+ variant="panel"
+ />
+
+ {error && (
+ <p role="alert" className="text-destructive text-sm">
+ {error}
+ </p>
+ )}
+
+ {parsedItems && (
+ <p className="text-muted-foreground text-sm">
+ {parsedItems.length} prompt
+ {parsedItems.length !== 1 ? "s" : ""} ready to import.
+ </p>
+ )}
+ </DialogBody>
+
+ <DialogFooter>
+ <Button
+ onClick={handleImport}
+ disabled={!parsedItems || isImportPending}
+ className="w-full"
+ >
+ {isImportPending ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ Importing…
+ </>
+ ) : (
+ "Import"
+ )}
+ </Button>
+ </DialogFooter>
+ </>
+ );
+};
+
+export function ImportPromptsButtonDialogController({
+ projectId,
+ children,
+}: {
+ projectId: string;
+ children: (control: {
+ disabled: { reason: string } | undefined;
+ openDialog: () => void;
+ }) => ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "prompts:CUD",
+ });
+ const utils = api.useUtils();
+ const importMutation = api.prompts.importBulk.useMutation({
+ onSuccess: () => utils.prompts.invalidate(),
+ });
+
+ const disabled = hasAccess
+ ? undefined
+ : { reason: "You don't have permission to import prompts." };
+
+ const openDialog = () => {
+ if (!hasAccess) return;
+
+ setOpen(true);
+ };
+
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen && importMutation.isPending) return;
+
+ setOpen(nextOpen);
+ };
+
+ return (
+ <Dialog open={hasAccess && open} onOpenChange={handleOpenChange}>
+ {children({ disabled, openDialog })}
+ <DialogContent className="max-h-[90vh] min-h-0 sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Import prompts</DialogTitle>
+ </DialogHeader>
+ <ImportPromptsDialogContent
+ isImportPending={importMutation.isPending}
+ onClose={() => handleOpenChange(false)}
+ onImport={(items) =>
+ importMutation.mutateAsync({ projectId, prompts: items })
+ }
+ />
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/features/prompts/server/actions/createPrompt.ts b/web/src/features/prompts/server/actions/createPrompt.ts
index ef483ef3f8..607d117315 100644
--- a/web/src/features/prompts/server/actions/createPrompt.ts
+++ b/web/src/features/prompts/server/actions/createPrompt.ts
@@ -18,6 +18,7 @@ import {
PromptService,
escapeSqlLikePattern,
redis,
+ logger,
extractPlaceholderNames,
type PromptResult,
} from "@langfuse/shared/src/server";
@@ -206,30 +207,55 @@ export const createPrompt = async ({
...PromptDependency[],
];
- // Rotate cache epoch only after successful commit.
- await promptService.invalidateCache({ projectId });
-
- const updatedPrompts = await prisma.prompt.findMany({
- where: {
- id: { in: touchedPromptIds },
- projectId,
- },
- });
+ // Once the transaction commits, side-effect failures must not report the
+ // persisted prompt as failed and cause callers to create another version.
+ try {
+ await promptService.invalidateCache({ projectId });
+ } catch (error) {
+ logger.error(
+ `Failed to invalidate prompt cache after creating prompt ${createdPrompt.id} in project ${projectId}`,
+ error,
+ );
+ }
- await Promise.all([
- ...updatedPrompts.map(async (prompt) =>
+ try {
+ const updatedPrompts = await prisma.prompt.findMany({
+ where: {
+ id: { in: touchedPromptIds },
+ projectId,
+ },
+ });
+ const eventPromises = updatedPrompts.map(async (prompt) =>
promptChangeEventSourcing(
await promptService.resolvePrompt(prompt),
"updated",
user,
),
- ),
- promptChangeEventSourcing(
- await promptService.resolvePrompt(createdPrompt),
- "created",
- user,
- ),
- ]);
+ );
+ eventPromises.push(
+ (async () =>
+ promptChangeEventSourcing(
+ await promptService.resolvePrompt(createdPrompt),
+ "created",
+ user,
+ ))(),
+ );
+
+ const eventResults = await Promise.allSettled(eventPromises);
+ for (const result of eventResults) {
+ if (result.status === "rejected") {
+ logger.error(
+ `Failed to publish prompt change event after creating prompt ${createdPrompt.id} in project ${projectId}`,
+ result.reason,
+ );
+ }
+ }
+ } catch (error) {
+ logger.error(
+ `Failed to prepare prompt change events after creating prompt ${createdPrompt.id} in project ${projectId}`,
+ error,
+ );
+ }
return createdPrompt;
};
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index 87f6e882f1..ef41c9b160 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -15,6 +15,7 @@ import {
import { checkHasProtectedLabels } from "../utils/checkHasProtectedLabels";
import {
CommentObjectType,
+ CreatePromptSchema,
CreatePromptTRPCSchema,
LATEST_PROMPT_LABEL,
optionalPaginationZod,
@@ -45,6 +46,7 @@ import {
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
import { TRPCError } from "@trpc/server";
import { promptChangeEventSourcing } from "@/src/features/prompts/server/promptChangeEventSourcing";
+import { hasEntitlementLimit } from "@/src/features/entitlements/server/hasEntitlementLimit";
const buildPathPrefixFilter = (pathPrefix?: string): Prisma.Sql => {
if (!pathPrefix) {
@@ -1516,6 +1518,206 @@ export const promptRouter = createTRPCRouter({
return { success: true };
}),
+
+ exportAll: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ includeAllVersions: z.boolean().default(false),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "prompts:read",
+ });
+
+ const count = await ctx.prisma.prompt.count({
+ where: { projectId: input.projectId },
+ });
+
+ if (count > 10_000) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Project has ${count} prompt versions which exceeds the export limit of 10,000. Please contact support for bulk exports of large projects.`,
+ });
+ }
+
+ const prompts = await ctx.prisma.prompt.findMany({
+ where: { projectId: input.projectId },
+ orderBy: [{ name: "asc" }, { version: "asc" }],
+ select: {
+ name: true,
+ version: true,
+ type: true,
+ prompt: true,
+ config: true,
+ tags: true,
+ labels: true,
+ commitMessage: true,
+ },
+ });
+
+ if (input.includeAllVersions) {
+ return prompts;
+ }
+
+ // Return only latest version per prompt name
+ const latestByName = new Map<string, (typeof prompts)[number]>();
+ for (const p of prompts) {
+ const existing = latestByName.get(p.name);
+ if (!existing || p.version > existing.version) {
+ latestByName.set(p.name, p);
+ }
+ }
+ return Array.from(latestByName.values());
+ }),
+
+ importBulk: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ prompts: z.array(CreatePromptSchema).max(500),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "prompts:CUD",
+ });
+
+ const importItems = input.prompts.map((item) => ({
+ item,
+ labels: item.labels.filter(
+ (label) => label !== "latest" && label !== "production",
+ ),
+ }));
+
+ const promptLimit = hasEntitlementLimit({
+ entitlementLimit: "prompt-management-count-prompts",
+ sessionUser: ctx.session.user,
+ projectId: input.projectId,
+ });
+
+ if (promptLimit !== false) {
+ const importedPromptNames = Array.from(
+ new Set(importItems.map(({ item }) => item.name)),
+ );
+ const [existingImportedPrompts, promptCountRows] = await Promise.all([
+ ctx.prisma.prompt.groupBy({
+ by: ["name"],
+ where: {
+ projectId: input.projectId,
+ name: { in: importedPromptNames },
+ },
+ }),
+ ctx.prisma.$queryRaw<Array<{ count: bigint }>>(Prisma.sql`
+ SELECT COUNT(DISTINCT name) AS count
+ FROM prompts
+ WHERE project_id = ${input.projectId}
+ `),
+ ]);
+ const existingImportedPromptNames = new Set(
+ existingImportedPrompts.map(({ name }) => name),
+ );
+ const newPromptCount = importedPromptNames.filter(
+ (name) => !existingImportedPromptNames.has(name),
+ ).length;
+ const currentPromptCount = Number(promptCountRows[0]?.count ?? 0);
+
+ if (
+ newPromptCount > 0 &&
+ currentPromptCount + newPromptCount > promptLimit
+ ) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: `Import would create ${newPromptCount} new prompts and exceed the project limit of ${promptLimit} prompts (${currentPromptCount} existing).`,
+ });
+ }
+ }
+
+ const { hasProtectedLabels, protectedLabels } =
+ await checkHasProtectedLabels({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ labelsToCheck: importItems.flatMap(({ labels }) => labels),
+ });
+
+ if (hasProtectedLabels) {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "promptProtectedLabels:CUD",
+ forbiddenErrorMessage: `You don't have permission to import prompts with protected labels. Please contact your project admin for assistance.\n\n Protected labels are: ${protectedLabels.join(", ")}`,
+ });
+ }
+
+ const results: Array<{
+ name: string;
+ success: boolean;
+ error?: string;
+ }> = [];
+
+ for (const { item, labels } of importItems) {
+ try {
+ const sharedParams = {
+ projectId: input.projectId,
+ name: item.name,
+ config: item.config ?? {},
+ tags: item.tags ?? [],
+ labels,
+ commitMessage: item.commitMessage ?? null,
+ createdBy: ctx.session.user.id,
+ prisma: ctx.prisma,
+ user: {
+ id: ctx.session.user.id,
+ name: ctx.session.user.name ?? null,
+ email: ctx.session.user.email ?? null,
+ },
+ };
+ let createdPrompt;
+ if (item.type === "chat") {
+ createdPrompt = await createPrompt({
+ ...sharedParams,
+ type: PromptType.Chat,
+ prompt: item.prompt,
+ });
+ } else {
+ createdPrompt = await createPrompt({
+ ...sharedParams,
+ type: PromptType.Text,
+ prompt: item.prompt,
+ });
+ }
+ await auditLog(
+ {
+ session: ctx.session,
+ resourceType: "prompt",
+ resourceId: createdPrompt.id,
+ action: "create",
+ after: createdPrompt,
+ },
+ ctx.prisma,
+ ).catch((error) => {
+ logger.error(
+ `Failed to create audit log for bulk-imported prompt ${createdPrompt.id} in project ${input.projectId}`,
+ error,
+ );
+ });
+ results.push({ name: item.name, success: true });
+ } catch (e) {
+ results.push({
+ name: item.name,
+ success: false,
+ error: e instanceof Error ? e.message : "Unknown error",
+ });
+ }
+ }
+
+ return { results };
+ }),
});
const getScoresForPromptIds = async (
diff --git a/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
index f09b06f678..cbafa7e6f1 100644
--- a/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
+++ b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
@@ -3,15 +3,25 @@ import { ActionButton } from "@/src/components/ActionButton";
import Page from "@/src/components/layouts/page";
import { PromptTable } from "@/src/features/prompts/components/prompts-table";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
-import { PlusIcon } from "lucide-react";
+import { Download, UploadIcon, PlusIcon } from "lucide-react";
import { api } from "@/src/utils/api";
import { PromptsOnboarding } from "@/src/components/onboarding/PromptsOnboarding";
import { useEntitlementLimit } from "@/src/features/entitlements/hooks";
import { PromptDetail } from "@/src/features/prompts/components/prompt-detail";
import PromptMetrics from "./metrics";
import { useQueryParams, StringParam } from "use-query-params";
-import React from "react";
+import { useState } from "react";
import { AutomationButton } from "@/src/features/automations/components/AutomationButton";
+import { ImportPromptsButtonDialogController } from "@/src/features/prompts/components/ImportPromptsButtonDialogController";
+import { Button } from "@/src/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/src/components/ui/dropdown-menu";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { toast } from "sonner";
export default function PromptsWithFolder() {
const router = useRouter();
@@ -40,7 +50,37 @@ export default function PromptsWithFolder() {
projectId,
scope: "prompts:CUD",
});
+ const hasReadAccess = useHasProjectAccess({
+ projectId,
+ scope: "prompts:read",
+ });
const promptLimit = useEntitlementLimit("prompt-management-count-prompts");
+ const utils = api.useUtils();
+ const [isExporting, setIsExporting] = useState(false);
+ const capture = usePostHogClientCapture();
+
+ const handleExport = async (mode: "latest" | "all") => {
+ setIsExporting(true);
+ try {
+ const data = await utils.prompts.exportAll.fetch({
+ projectId,
+ includeAllVersions: mode === "all",
+ });
+ const json = JSON.stringify(data, null, 2);
+ const blob = new Blob([json], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `langfuse-prompts-${mode}-${new Date().toISOString().slice(0, 10)}.json`;
+ a.click();
+ URL.revokeObjectURL(url);
+ capture("prompts:bulk_export", { mode });
+ } catch {
+ toast.error("Failed to export prompts. Please try again.");
+ } finally {
+ setIsExporting(false);
+ }
+ };
// Check if the project has any prompts
const { data: hasAnyPrompt, isLoading } = api.prompts.hasAny.useQuery(
@@ -89,6 +129,39 @@ export default function PromptsWithFolder() {
actionButtonsRight: (
<>
{projectId && <AutomationButton projectId={projectId} />}
+ {hasReadAccess && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="outline" disabled={isExporting}>
+ <UploadIcon className="mr-1 h-4 w-4" />
+ {isExporting ? "Exporting…" : "Export"}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => handleExport("latest")}>
+ Latest version per prompt
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => handleExport("all")}>
+ All versions
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {projectId && (
+ <ImportPromptsButtonDialogController projectId={projectId}>
+ {({ disabled, openDialog }) => (
+ <Button
+ variant="outline"
+ disabled={Boolean(disabled)}
+ title={disabled?.reason}
+ onClick={openDialog}
+ >
+ <Download className="mr-1 h-4 w-4" />
+ Import
+ </Button>
+ )}
+ </ImportPromptsButtonDialogController>
+ )}
<ActionButton
icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}
hasAccess={hasCUDAccess}