Skip to content

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

feat(prompts): virtual folders for prompt management (#7262)

Nimarca3791e66d58
diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.ts
index cc6049da4f..d6937ddc7f 100644
--- a/packages/shared/prisma/seed.ts
+++ b/packages/shared/prisma/seed.ts
@@ -1133,6 +1133,33 @@ export const SEED_PROMPTS = [
labels: ["production", "latest"],
tags: ["tag1", "tag2"],
},
+ {
+ id: `folder-customer-prompt-1`,
+ createdBy: "user-1",
+ prompt: "Folder prompt 1 content",
+ name: "folder/customer/prompt-1",
+ version: 1,
+ labels: ["production", "latest"],
+ tags: ["tag1", "tag2"],
+ },
+ {
+ id: `folder-customer-prompt-2`,
+ createdBy: "user-1",
+ prompt: "Folder prompt 2 content",
+ name: "folder/customer/prompt-2",
+ version: 1,
+ labels: ["production", "latest"],
+ tags: ["tag1", "tag2"],
+ },
+ {
+ id: `folder-prompt-1`,
+ createdBy: "user-1",
+ prompt: "Folder prompt 1 content",
+ name: "folder/prompt-1",
+ version: 1,
+ labels: ["production", "latest"],
+ tags: ["tag1", "tag2"],
+ },
];
export const PROMPT_IDS: string[] = [];
diff --git a/packages/shared/src/features/prompts/validation.ts b/packages/shared/src/features/prompts/validation.ts
new file mode 100644
index 0000000000..fb61b66541
--- /dev/null
+++ b/packages/shared/src/features/prompts/validation.ts
@@ -0,0 +1,15 @@
+import { z } from "zod/v4";
+
+/**
+ * Prompt name validation schema for API, tRPC and client
+ */
+export const PromptNameSchema = z
+ .string()
+ .min(1, "Enter a name")
+ .regex(/^[^|]*$/, "Prompt name cannot contain '|' character")
+ .regex(/^[^/]/, "Name cannot start with a slash")
+ .regex(/^(?!.*\/\/)/, "Name cannot contain consecutive slashes")
+ .regex(/^.*[^/]$/, "Name cannot end with a slash")
+ .transform((s) => s.trim())
+ .refine((s) => s.length > 0, "Name cannot be empty")
+ .refine((name) => name !== "new", "Prompt name cannot be 'new'");
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index c3f0565d29..0096fcd10b 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -42,6 +42,7 @@ export * from "./features/experiments/utils";
// prompts
export * from "./features/prompts/parsePromptDependencyTags";
+export * from "./features/prompts/validation";
// export db types only
export * from "@prisma/client";
diff --git a/web/src/__tests__/prompts.v2.servertest.ts b/web/src/__tests__/prompts.v2.servertest.ts
index 186c6a388c..a98e7820ea 100644
--- a/web/src/__tests__/prompts.v2.servertest.ts
+++ b/web/src/__tests__/prompts.v2.servertest.ts
@@ -696,6 +696,65 @@ describe("/api/public/v2/prompts API Endpoint", () => {
expect(fetchedPrompt.body.config).toEqual({});
});
+ describe("prompt name validation", () => {
+ const testInvalidName = async (name: string, expectedError: string) => {
+ const response = await makeAPICall("POST", baseURI, {
+ name,
+ prompt: "test prompt",
+ type: "text",
+ });
+ expect(response.status).toBe(400);
+ expect(response.body.message).toBe("Invalid request data");
+ const hasExpectedMessage = JSON.stringify(response.body.error).includes(`"message":"${expectedError}"`);
+ expect(hasExpectedMessage).toBe(true);
+ };
+
+ const testValidName = async (name: string) => {
+ const response = await makeAPICall("POST", baseURI, {
+ name,
+ prompt: "test prompt",
+ type: "text",
+ });
+ expect(response.status).toBe(201);
+ await prisma.prompt.deleteMany({
+ where: { name, projectId },
+ });
+ };
+
+ it("should reject invalid prompt names", async () => {
+ // Test invalid patterns
+ await testInvalidName("/invalid-name", "Name cannot start with a slash");
+ await testInvalidName("invalid-name/", "Name cannot end with a slash");
+ await testInvalidName("invalid//name", "Name cannot contain consecutive slashes");
+ await testInvalidName("invalid|name", "Prompt name cannot contain '|' character");
+ await testInvalidName("new", "Prompt name cannot be 'new'");
+ await testInvalidName("", "Enter a name");
+ });
+
+ it("should accept valid prompt names", async () => {
+ const validNames = [
+ "simple-name",
+ "name_with_underscores",
+ "name.with.dots",
+ "UPPERCASE",
+ "folder/subfolder/name",
+ "name-with-123-numbers",
+ "_starting_with_underscore",
+ "ending_with_underscore_",
+ "multiple___underscores",
+ "multiple---hyphens",
+ "multiple...dots",
+ "name with spaces",
+ "multiple spaces",
+ "angled[brac]es]",
+ ];
+
+ for (const name of validNames) {
+ await testValidName(name);
+ }
+ });
+ });
+
it("should update tags across versions", async () => {
const promptName = "prompt-name" + nanoid();
@@ -760,6 +819,37 @@ describe("/api/public/v2/prompts API Endpoint", () => {
expect(fetchedPrompt4.tags).toEqual([]);
expect(fetchedPrompt4.version).toBe(4);
});
+
+ it("should create and fetch a test prompt with slashes in the name", async () => {
+ const promptName = "this/is/a/prompt/with/a/slash" + nanoid();
+
+ const response = await makeAPICall("POST", baseURI, {
+ name: promptName,
+ prompt: "This is a prompt in a folder structure",
+ type: "text",
+ labels: ["production"],
+ commitMessage: "chore: setup folder structure prompt",
+ });
+
+ expect(response.status).toBe(201);
+
+ const { body: fetchedPrompt } = await makeAPICall(
+ "GET",
+ `${baseURI}/${encodeURIComponent(promptName)}`,
+ undefined,
+ );
+
+ const validatedPrompt = validatePrompt(fetchedPrompt);
+ // expect(fetchedPrompt.status).toBe(200);
+ // if (!isPrompt(fetchedPrompt.body)) {
+ // throw new Error("Expected body to be a prompt");
+ // }
+
+ // Verify the name with slashes is preserved
+ expect(validatedPrompt.name).toBe(promptName);
+ expect(validatedPrompt.name).toContain("/");
+ expect(validatedPrompt.prompt).toBe("This is a prompt in a folder structure");
+ });
});
describe("when fetching a prompt list", () => {
@@ -2016,6 +2106,7 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {
type: "text",
},
{ name: "prompt with spaces", prompt: "Space content", type: "text" },
+ { name: "prompt/with/slashes", prompt: "Slash content", type: "text" },
];
// Create all the special character prompts
@@ -2037,6 +2128,7 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {
@@@langfusePrompt:name=prompt.with.dots|version=1@@@
@@@langfusePrompt:name=prompt123WithNumbers|version=1@@@
@@@langfusePrompt:name=prompt with spaces|version=1@@@
+ @@@langfusePrompt:name=prompt/with/slashes|version=1@@@
`;
await makeAPICall(
@@ -2070,6 +2162,7 @@ describe("PATCH api/public/v2/prompts/[promptName]/versions/[version]", () => {
Dot content
Number content
Space content
+ Slash content
`;
expect(parsedPrompt).toBe(expectedPrompt);
}, 10_000);
diff --git a/web/src/components/table/table-link.tsx b/web/src/components/table/table-link.tsx
index 0217368234..79783007eb 100644
--- a/web/src/components/table/table-link.tsx
+++ b/web/src/components/table/table-link.tsx
@@ -6,6 +6,8 @@ export type TableLinkProps = {
value: string;
icon?: React.ReactNode;
className?: string;
+ onClick?: (event: React.MouseEvent) => void;
+ title?: string;
};
export default function TableLink({
@@ -13,7 +15,16 @@ export default function TableLink({
value,
icon,
className,
+ onClick,
+ title,
}: TableLinkProps) {
+ const handleClick = (event: React.MouseEvent) => {
+ if (onClick) {
+ event.preventDefault();
+ onClick(event);
+ }
+ };
+
return (
<Link
className={cn(
@@ -21,8 +32,9 @@ export default function TableLink({
className,
)}
href={path}
- title={value}
+ title={title || value}
prefetch={false}
+ onClick={handleClick}
>
{icon ? icon : value}
</Link>
diff --git a/web/src/features/prompts/components/NewPromptForm/index.tsx b/web/src/features/prompts/components/NewPromptForm/index.tsx
index 53ed798042..f29a1caea0 100644
--- a/web/src/features/prompts/components/NewPromptForm/index.tsx
+++ b/web/src/features/prompts/components/NewPromptForm/index.tsx
@@ -61,6 +61,7 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
const { onFormSuccess, initialPrompt } = props;
const projectId = useProjectIdFromURL();
const [shouldLoadPlaygroundCache] = useQueryParam("loadPlaygroundCache");
+ const [folderPath] = useQueryParam("folder");
const [formError, setFormError] = useState<string | null>(null);
const { playgroundCache } = usePlaygroundCache();
const [initialMessages, setInitialMessages] = useState<unknown>([]);
@@ -88,7 +89,7 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
initialPromptVariant?.type === PromptType.Text
? initialPromptVariant?.prompt
: "",
- name: initialPrompt?.name ?? "",
+ name: initialPrompt?.name ?? (folderPath ? `${folderPath}/` : ""),
config: JSON.stringify(initialPrompt?.config?.valueOf(), null, 2) || "{}",
isActive: !Boolean(initialPrompt),
commitMessage: initialPrompt?.commitMessage ?? undefined,
@@ -214,7 +215,7 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
- <Input placeholder="Select a prompt name" {...field} />
+ <Input placeholder="Name your prompt" {...field} />
</FormControl>
{/* Custom form message to include a link to the already existing prompt */}
{form.getFieldState("name").error ? (
diff --git a/web/src/features/prompts/components/NewPromptForm/validation.ts b/web/src/features/prompts/components/NewPromptForm/validation.ts
index 31e764bf03..74cb94f4b7 100644
--- a/web/src/features/prompts/components/NewPromptForm/validation.ts
+++ b/web/src/features/prompts/components/NewPromptForm/validation.ts
@@ -3,14 +3,12 @@ import { PromptType } from "@/src/features/prompts/server/utils/validation";
import {
PromptChatMessageListSchema,
TextPromptSchema,
+ PromptNameSchema,
} from "@langfuse/shared";
import { COMMIT_MESSAGE_MAX_LENGTH } from "@/src/features/prompts/constants";
const NewPromptBaseSchema = z.object({
- name: z
- .string()
- .min(1, "Enter a name")
- .regex(/^[^|]*$/, "Prompt name cannot contain '|' character"),
+ name: PromptNameSchema,
isActive: z.boolean({
error: "Enter whether the prompt should go live",
}),
diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsx
index be6953b24f..6161b27467 100644
--- a/web/src/features/prompts/components/prompt-detail.tsx
+++ b/web/src/features/prompts/components/prompt-detail.tsx
@@ -64,7 +64,7 @@ const getPythonCode = (
# Initialize Langfuse client
langfuse = Langfuse()
-# Get production prompt
+# Get production prompt
prompt = langfuse.get_prompt("${name}")
# Get by label
@@ -84,7 +84,7 @@ const getJsCode = (
// Initialize the Langfuse client
const langfuse = new Langfuse();
-// Get production prompt
+// Get production prompt
const prompt = await langfuse.getPrompt("${name}");
// Get by label
@@ -98,7 +98,20 @@ langfuse.getPrompt("${name}", ${version})
export const PromptDetail = () => {
const projectId = useProjectIdFromURL();
const capture = usePostHogClientCapture();
- const promptName = decodeURIComponent(useRouter().query.promptName as string);
+ const router = useRouter();
+
+ // Handle both [promptName] route and catch-all [...folder] route
+ const promptName = router.query.promptName
+ ? decodeURIComponent(router.query.promptName as string)
+ : (() => {
+ const folder = router.query.folder;
+ if (Array.isArray(folder)) {
+ return folder.join('/');
+ } else if (typeof folder === 'string') {
+ return folder;
+ }
+ return '';
+ })();
const [currentPromptVersion, setCurrentPromptVersion] = useQueryParam(
"version",
NumberParam,
diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsx
index 597ddecb26..c1f806d965 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -1,4 +1,4 @@
-import { useEffect } from "react";
+import { useEffect, useMemo } from "react";
import { DataTable } from "@/src/components/table/data-table";
import TableLink from "@/src/components/table/table-link";
import { type LangfuseColumnDef } from "@/src/components/table/types";
@@ -12,23 +12,69 @@ import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import { promptsTableColsWithOptions } from "@/src/server/api/definitions/promptsTable";
-import { NumberParam, useQueryParams, withDefault } from "use-query-params";
+import { NumberParam, StringParam, useQueryParams, withDefault } from "use-query-params";
import { createColumnHelper } from "@tanstack/react-table";
import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";
import { Skeleton } from "@/src/components/ui/skeleton";
import { useDebounce } from "@/src/hooks/useDebounce";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
+import {
+ Breadcrumb,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbList,
+ BreadcrumbPage,
+ BreadcrumbSeparator,
+} from "@/src/components/ui/breadcrumb";
+import { Slash, Folder, Home } from "lucide-react";
type PromptTableRow = {
+ id: string;
name: string;
- version: number;
- createdAt: Date;
- labels: string[];
- type: string;
- numberOfObservations: number;
- tags: string[];
+ type: "folder" | "text" | "chat";
+ version?: number;
+ createdAt?: Date;
+ labels?: string[];
+ numberOfObservations?: number;
+ tags?: string[];
};
+function createRow(
+ data: Partial<PromptTableRow> & { id: string; name: string; type: "folder" | "text" | "chat" }
+): PromptTableRow {
+ return {
+ version: undefined,
+ createdAt: undefined,
+ labels: [],
+ tags: [],
+ numberOfObservations: undefined,
+ ...data,
+ };
+}
+
+function isFolder(row: PromptTableRow): row is PromptTableRow & { type: "folder" } {
+ return row.type === "folder";
+}
+
+function getDisplayName(fullPath: string, currentFolderPath: string): string {
+ return currentFolderPath === ''
+ ? fullPath
+ : fullPath.substring(currentFolderPath.length + 1);
+}
+
+function createBreadcrumbItems(currentFolderPath: string) {
+ if (!currentFolderPath) return [];
+
+ const segments = currentFolderPath.split('/');
+ return segments.map((name, i) => {
+ const folderPath = segments.slice(0, i + 1).join('/');
+ return {
+ name,
+ folderPath,
+ };
+ });
+}
+
export function PromptTable() {
const projectId = useProjectIdFromURL();
const { setDetailPageList } = useDetailPageLists();
@@ -43,11 +89,19 @@ export function PromptTable() {
column: "createdAt",
order: "DESC",
});
- const [paginationState, setPaginationState] = useQueryParams({
+ const [queryParams, setQueryParams] = useQueryParams({
pageIndex: withDefault(NumberParam, 0),
pageSize: withDefault(NumberParam, 50),
+ folder: StringParam,
});
+ const paginationState = {
+ pageIndex: queryParams.pageIndex,
+ pageSize: queryParams.pageSize,
+ };
+
+ const currentFolderPath = queryParams.folder || '';
+
const prompts = api.prompts.all.useQuery(
{
page: paginationState.pageIndex,
@@ -55,6 +109,7 @@ export function PromptTable() {
projectId: projectId as string, // Typecast as query is enabled only when projectId is present
filter: filterState,
orderBy: orderByState,
+ pathPrefix: currentFolderPath,
},
{
enabled: Boolean(projectId),
@@ -97,6 +152,80 @@ export function PromptTable() {
})),
);
+ // Filter and group prompts based on current folder path
+ const processedRowData = useMemo(() => {
+ if (!promptsRowData.rows) return { ...promptsRowData, rows: [] };
+
+ const uniqueFolders = new Set<string>();
+ const matchingPrompts: typeof promptsRowData.rows = [];
+
+ // Identify immediate subfolders from backend-filtered prompts
+ for (const prompt of promptsRowData.rows) {
+ const promptName = prompt.id;
+
+ if (currentFolderPath) {
+ const prefix = `${currentFolderPath}/`;
+ if (promptName.startsWith(prefix)) {
+ const remainingPath = promptName.substring(prefix.length);
+ const slashIndex = remainingPath.indexOf('/');
+
+ if (slashIndex > 0) {
+ // Subfolder
+ const subFolderName = remainingPath.substring(0, slashIndex);
+ const fullSubFolderPath = `${currentFolderPath}/${subFolderName}`;
+ uniqueFolders.add(fullSubFolderPath);
+ } else {
+ // Direct prompt in current folder
+ matchingPrompts.push(prompt);
+ }
+ }
+ } else {
+ // Root level
+ const slashIndex = promptName.indexOf('/');
+ if (slashIndex > 0) {
+ const folderName = promptName.substring(0, slashIndex);
+ uniqueFolders.add(folderName);
+ } else {
+ matchingPrompts.push(prompt);
+ }
+ }
+ }
+
+ // Create combined rows: folders first, then prompts
+ const combinedRows: PromptTableRow[] = [];
+
+ // Add folder rows
+ for (const folderPath of uniqueFolders) {
+ const folderName = getDisplayName(folderPath, currentFolderPath);
+ combinedRows.push(createRow({
+ id: folderPath,
+ name: folderName,
+ type: "folder",
+ }));
+ }
+
+ // Add matching prompts
+ for (const prompt of matchingPrompts) {
+ combinedRows.push(
+ createRow({
+ id: prompt.id,
+ name: prompt.id,
+ type: prompt.type as "text" | "chat",
+ version: prompt.version,
+ createdAt: prompt.createdAt,
+ labels: prompt.labels,
+ tags: prompt.tags,
+ numberOfObservations: Number(prompt.observationCount ?? 0),
+ })
+ );
+ }
+
+ return {
+ ...promptsRowData,
+ rows: combinedRows,
+ };
+ }, [promptsRowData, currentFolderPath]);
+
const promptFilterOptions = api.prompts.filterOptions.useQuery(
{
projectId: projectId as string,
@@ -136,9 +265,36 @@ export function PromptTable() {
size: 250,
cell: (row) => {
const name = row.getValue();
+ const rowData = row.row.original;
+
+ if (isFolder(rowData)) {
+ const displayName = getDisplayName(rowData.id, currentFolderPath);
+ return (
+ <TableLink
+ path={""}
+ value={displayName} // To satisfy table-link, fallback
+ className="flex items-center gap-2"
+ icon={
+ <>
+ <Folder className="h-4 w-4" />
+ {displayName}
+ </>
+ }
+ onClick={() => {
+ setQueryParams({
+ folder: rowData.id,
+ pageIndex: 0,
+ pageSize: queryParams.pageSize
+ });
+ }}
+ title={displayName || ""}
+ />
+ );
+ }
+
return name ? (
<TableLink
- path={`/project/${projectId}/prompts/${encodeURIComponent(name)}`}
+ path={`/project/${projectId}/prompts/${encodeURIComponent(rowData.id)}`}
value={name}
/>
) : undefined;
@@ -150,6 +306,7 @@ export function PromptTable() {
enableSorting: true,
size: 70,
cell: (row) => {
+ if (isFolder(row.row.original)) return null;
return row.getValue();
},
}),
@@ -168,18 +325,21 @@ export function PromptTable() {
enableSorting: true,
size: 200,
cell: (row) => {
+ if (isFolder(row.row.original)) return null;
const createdAt = row.getValue();
- return <LocalIsoDate date={createdAt} />;
+ return createdAt ? <LocalIsoDate date={createdAt} /> : null;
},
}),
columnHelper.accessor("numberOfObservations", {
header: "Number of Observations",
size: 170,
cell: (row) => {
+ if (isFolder(row.row.original)) return null;
+
const numberOfObservations = row.getValue();
- const name = row.row.original.name;
+ const promptId = row.row.original.id;
const filter = encodeURIComponent(
- `promptName;stringOptions;;any of;${name}`,
+ `promptName;stringOptions;;any of;${promptId}`,
);
if (!promptMetrics.isSuccess) {
return <Skeleton className="h-3 w-1/2" />;
@@ -187,7 +347,7 @@ export function PromptTable() {
return (
<TableLink
path={`/project/${projectId}/observations?filter=${numberOfObservations ? filter : ""}`}
- value={numberOfObservations.toLocaleString()}
+ value={numberOfObservations?.toLocaleString() ?? ""}
/>
);
},
@@ -198,14 +358,17 @@ export function PromptTable() {
enableSorting: true,
size: 120,
cell: (row) => {
+ // height h-6 to ensure consistent row height for normal & folder rows
+ if (isFolder(row.row.original)) return <div className="h-6" />;
+
const tags = row.getValue();
- const promptName: string = row.row.original.name;
+ const promptId = row.row.original.id;
return (
<TagPromptPopover
- tags={tags}
+ tags={tags ?? []}
availableTags={allTags}
projectId={projectId as string}
- promptName={promptName}
+ promptName={promptId}
promptsFilter={{
page: 0,
limit: 50,
@@ -223,14 +386,63 @@ export function PromptTable() {
header: "Actions",
size: 70,
cell: (row) => {
- const name = row.row.original.name;
- return <DeletePrompt promptName={name} />;
+ if (isFolder(row.row.original)) return null;
+
+ const promptId = row.row.original.id;
+ return <DeletePrompt promptName={promptId} />;
},
}),
] as LangfuseColumnDef<PromptTableRow>[];
return (
<>
+ {currentFolderPath && (
+ <div className="pt-2 ml-2">
+ <Breadcrumb>
+ <BreadcrumbList>
+ <BreadcrumbItem>
+ <BreadcrumbLink
+ className="cursor-pointer hover:underline"
+ onClick={() => {
+ setQueryParams({
+ folder: undefined,
+ pageIndex: 0,
+ pageSize: queryParams.pageSize
+ });
+ }}
+ >
+ <Home className="h-4 w-4" />
+ </BreadcrumbLink>
+ </BreadcrumbItem>
+ {createBreadcrumbItems(currentFolderPath).flatMap((item, index, array) => [
+ index > 0 && (
+ <BreadcrumbSeparator key={`sep-${item.folderPath}`}>
+ <Slash />
+ </BreadcrumbSeparator>
+ ),
+ <BreadcrumbItem key={item.folderPath}>
+ {index === array.length - 1 ? (
+ <BreadcrumbPage>{item.name}</BreadcrumbPage>
+ ) : (
+ <BreadcrumbLink
+ className="cursor-pointer hover:underline"
+ onClick={() => {
+ setQueryParams({
+ folder: item.folderPath,
+ pageIndex: 0,
+ pageSize: queryParams.pageSize
+ });
+ }}
+ >
+ {item.name}
+ </BreadcrumbLink>
+ )}
+ </BreadcrumbItem>
+ ])}
+ </BreadcrumbList>
+ </Breadcrumb>
+ </div>
+ )}
<DataTableToolbar
columns={promptColumns}
filterColumnDefinition={promptsTableColsWithOptions(
@@ -254,14 +466,18 @@ export function PromptTable() {
: {
isLoading: false,
isError: false,
- data: promptsRowData.rows?.map((item) => ({
+ data: processedRowData.rows?.map((item) => ({
id: item.id,
- name: item.id, // was renamed to id to match the core and metrics
+ name: item.type === 'folder'
+ ? item.name
+ : currentFolderPath
+ ? item.name.substring(currentFolderPath.length + 1)
+ : item.name,
version: item.version,
createdAt: item.createdAt,
type: item.type,
labels: item.labels,
- numberOfObservations: Number(item.observationCount ?? 0),
+ numberOfObservations: item.numberOfObservations,
tags: item.tags,
})),
}
@@ -270,7 +486,12 @@ export function PromptTable() {
setOrderBy={setOrderByState}
pagination={{
totalCount,
- onChange: setPaginationState,
+ onChange: (newPaginationState) => {
+ setQueryParams({
+ ...queryParams,
+ ...newPaginationState,
+ });
+ },
state: paginationState,
}}
/>
diff --git a/web/src/features/prompts/hooks/usePromptNameValidation.tsx b/web/src/features/prompts/hooks/usePromptNameValidation.tsx
index 0bc3ec027a..515fbddfba 100644
--- a/web/src/features/prompts/hooks/usePromptNameValidation.tsx
+++ b/web/src/features/prompts/hooks/usePromptNameValidation.tsx
@@ -13,7 +13,7 @@ export const usePromptNameValidation = ({
form,
}: UsePromptNameValidationProps) => {
useEffect(() => {
- if (!currentName) return;
+ if (!currentName || !allPrompts) return;
const isNewPrompt = !allPrompts
?.map((prompt) => prompt.value)
@@ -21,15 +21,11 @@ export const usePromptNameValidation = ({
if (!isNewPrompt) {
form.setError("name", { message: "Prompt name already exists." });
- } 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");
+ const currentError = form.getFieldState("name").error;
+ if (currentError?.message === "Prompt name already exists.") {
+ form.clearErrors("name");
+ }
}
}, [currentName, allPrompts, form]);
};
diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.ts
index de36ec4769..dc7c297631 100644
--- a/web/src/features/prompts/server/routers/promptRouter.ts
+++ b/web/src/features/prompts/server/routers/promptRouter.ts
@@ -41,6 +41,7 @@ const PromptFilterOptions = z.object({
filter: z.array(singleFilter),
orderBy: orderBy,
...paginationZod,
+ pathPrefix: z.string().optional(),
});
export const promptRouter = createTRPCRouter({
@@ -87,11 +88,15 @@ export const promptRouter = createTRPCRouter({
"prompts",
);
+ const pathFilter = input.pathPrefix
+ ? Prisma.sql` AND (p.name LIKE ${input.pathPrefix + '/%'} OR p.name = ${input.pathPrefix})`
+ : Prisma.empty;
+
const [prompts, promptCount] = await Promise.all([
// prompts
ctx.prisma.$queryRaw<Array<Prompt>>(
generatePromptQuery(
- Prisma.sql`
+ Prisma.sql`
p.id,
p.name,
p.version,
@@ -107,6 +112,7 @@ export const promptRouter = createTRPCRouter({
orderByCondition,
input.limit,
input.page,
+ pathFilter,
),
),
// promptCount
@@ -117,7 +123,8 @@ export const promptRouter = createTRPCRouter({
filterCondition,
Prisma.empty,
1, // limit
- 0, // page
+ 0, // page,
+ pathFilter,
),
),
]);
@@ -780,7 +787,7 @@ export const promptRouter = createTRPCRouter({
const labels = await ctx.prisma.$queryRaw<{ label: string }[]>`
SELECT DISTINCT UNNEST(labels) AS label
FROM prompts
- WHERE project_id = ${input.projectId}
+ WHERE project_id = ${input.projectId}
AND labels IS NOT NULL;
`;
@@ -826,7 +833,7 @@ export const promptRouter = createTRPCRouter({
});
const query = Prisma.sql`
- SELECT
+ SELECT
p.name,
array_agg(DISTINCT p.version) as "versions",
array_agg(DISTINCT l) FILTER (WHERE l IS NOT NULL) AS "labels"
@@ -1227,6 +1234,7 @@ const generatePromptQuery = (
orderCondition: Prisma.Sql,
limit: number,
page: number,
+ pathFilter: Prisma.Sql = Prisma.empty,
) => {
return Prisma.sql`
SELECT
@@ -1237,10 +1245,12 @@ const generatePromptQuery = (
FROM prompts p
WHERE "project_id" = ${projectId}
${filterCondition}
+ ${pathFilter}
GROUP BY name
)
AND "project_id" = ${projectId}
${filterCondition}
+ ${pathFilter}
${orderCondition}
LIMIT ${limit} OFFSET ${page * limit};
`;
diff --git a/web/src/features/prompts/server/utils/validation.ts b/web/src/features/prompts/server/utils/validation.ts
index 2bf8bd0afe..95c670437b 100644
--- a/web/src/features/prompts/server/utils/validation.ts
+++ b/web/src/features/prompts/server/utils/validation.ts
@@ -1,5 +1,5 @@
import { z } from "zod/v4";
-import { jsonSchema } from "@langfuse/shared";
+import { jsonSchema, PromptNameSchema } from "@langfuse/shared";
import type { Prompt } from "@langfuse/shared";
import { COMMIT_MESSAGE_MAX_LENGTH } from "@/src/features/prompts/constants";
@@ -22,13 +22,6 @@ export const PromptLabelSchema = z
"Label must be lowercase alphanumeric with optional underscores, hyphens, or periods",
);
-export const PromptNameSchema = z
- .string()
- .min(1)
- .regex(/^[^|]*$/, "Name cannot contain '|' character")
- .transform((s) => s.trim())
- .refine((s) => s.length > 0, "Name cannot be empty");
-
const BaseCreateTextPromptSchema = z.object({
name: PromptNameSchema,
labels: z.array(PromptLabelSchema).default([]),
diff --git a/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx b/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx
index eef69f3903..859f36a9fa 100644
--- a/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx
+++ b/web/src/features/scores/components/ScoreDetailColumnHelpers.tsx
@@ -10,7 +10,7 @@ import {
type NumericAggregate,
type ScoreAggregate,
} from "@langfuse/shared";
-import { type PromptVersionTableRow } from "@/src/pages/project/[projectId]/prompts/[promptName]/metrics";
+import type { PromptVersionTableRow } from "@/src/pages/project/[projectId]/prompts/metrics";
import { type ScoreDataType } from "@langfuse/shared";
import { type Row } from "@tanstack/react-table";
import React from "react";
diff --git a/web/src/features/scores/lib/types.ts b/web/src/features/scores/lib/types.ts
index aee884a9ba..237e164bbb 100644
--- a/web/src/features/scores/lib/types.ts
+++ b/web/src/features/scores/lib/types.ts
@@ -3,7 +3,7 @@ import { type SessionTableRow } from "@/src/components/table/use-cases/sessions"
import { type TracesTableRow } from "@/src/components/table/use-cases/traces";
import { type DatasetRunItemRowData } from "@/src/features/datasets/components/DatasetRunItemsTable";
import { type DatasetRunRowData } from "@/src/features/datasets/components/DatasetRunsTable";
-import { type PromptVersionTableRow } from "@/src/pages/project/[projectId]/prompts/[promptName]/metrics";
+import { type PromptVersionTableRow } from "@/src/pages/project/[projectId]/prompts/metrics";
import { type ScoreDataType, type ScoreSourceType } from "@langfuse/shared";
export type TableRowTypesWithIndividualScoreColumns =
diff --git a/web/src/pages/project/[projectId]/prompts/index.tsx b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
similarity index 66%
rename from web/src/pages/project/[projectId]/prompts/index.tsx
rename to web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
index 1217438817..2ecf528bf2 100644
--- a/web/src/pages/project/[projectId]/prompts/index.tsx
+++ b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
@@ -8,10 +8,24 @@ import { 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";
-export default function Prompts() {
+export default function PromptsWithFolder() {
const router = useRouter();
const projectId = router.query.projectId as string;
+ const routeSegments = router.query.folder;
+ const [queryParams] = useQueryParams({ folder: StringParam });
+ const folderQueryParam = queryParams.folder || '';
+
+ // Determine view type based on route segments
+ const segmentsArray = Array.isArray(routeSegments) ? routeSegments : [];
+ const isMetricsPage = segmentsArray.length > 0 && segmentsArray[segmentsArray.length - 1] === 'metrics';
+ const promptNameFromRoute = segmentsArray.length > 0
+ ? (isMetricsPage ? segmentsArray.slice(0, -1).join('/') : segmentsArray.join('/'))
+ : '';
+
const capture = usePostHogClientCapture();
const hasCUDAccess = useHasProjectAccess({
projectId,
@@ -35,7 +49,7 @@ export default function Prompts() {
const { data: count } = api.prompts.count.useQuery(
{ projectId },
{
- enabled: !!projectId,
+ enabled: !!projectId && !promptNameFromRoute, // Only count when on folder view
trpc: {
context: {
skipBatch: true,
@@ -46,6 +60,14 @@ export default function Prompts() {
const showOnboarding = !isLoading && !hasAnyPrompt;
+ // Decide what to render: metrics, detail, or folder view
+ if (promptNameFromRoute.length > 0) {
+ if (isMetricsPage) {
+ return <PromptMetrics />;
+ }
+ return <PromptDetail />;
+ }
+
return (
<Page
headerProps={{
@@ -59,7 +81,7 @@ export default function Prompts() {
<ActionButton
icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}
hasAccess={hasCUDAccess}
- href={`/project/${projectId}/prompts/new`}
+ href={`/project/${projectId}/prompts/new${folderQueryParam ? `?folder=${encodeURIComponent(folderQueryParam)}` : ''}`}
variant="default"
limit={promptLimit}
limitValue={Number(count?.totalCount ?? 0)}
@@ -77,7 +99,7 @@ export default function Prompts() {
{showOnboarding ? (
<PromptsOnboarding projectId={projectId} />
) : (
- <PromptTable />
+ <PromptTable key={folderQueryParam} />
)}
</Page>
);
diff --git a/web/src/pages/project/[projectId]/prompts/[promptName]/metrics.tsx b/web/src/pages/project/[projectId]/prompts/metrics.tsx
similarity index 100%
rename from web/src/pages/project/[projectId]/prompts/[promptName]/metrics.tsx
rename to web/src/pages/project/[projectId]/prompts/metrics.tsx
diff --git a/web/src/pages/project/[projectId]/prompts/[promptName]/index.tsx b/web/src/pages/project/[projectId]/prompts/prompt-detail.tsx
similarity index 100%
rename from web/src/pages/project/[projectId]/prompts/[promptName]/index.tsx
rename to web/src/pages/project/[projectId]/prompts/prompt-detail.tsx