🪢 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(ui): add improved prompt ui (#961)
Richard Krümmelff303750cced
diff --git a/src/components/delete-trace.tsx b/src/components/delete-trace.tsxindex d51314a986..5cc484d35c 100644--- a/src/components/delete-trace.tsx+++ b/src/components/delete-trace.tsx@@ -52,7 +52,7 @@ export function DeleteTrace({<TrashIcon className="h-4 w-4" /></Button>) : (- <Button variant="outline" type="button" size="sm">+ <Button variant="outline" type="button" size="icon"><TrashIcon className="h-4 w-4" /></Button>)}diff --git a/src/features/prompts/components/new-prompt-button.tsx b/src/features/prompts/components/new-prompt-button.tsxindex 2dcbc051cb..ab4f61446a 100644--- a/src/features/prompts/components/new-prompt-button.tsx+++ b/src/features/prompts/components/new-prompt-button.tsx@@ -155,7 +155,7 @@ export const NewPromptForm = (props: {// go to the following page after creating the promptif (newPrompt) {void router.push(- `/project/${props.projectId}/prompts/${newPrompt.id}`,+ `/project/${props.projectId}/prompts/${newPrompt.name}`,);}})diff --git a/src/features/prompts/components/promote-prompt.tsx b/src/features/prompts/components/promote-prompt.tsxindex eee70558d4..7c007fda2b 100644--- a/src/features/prompts/components/promote-prompt.tsx+++ b/src/features/prompts/components/promote-prompt.tsx@@ -15,21 +15,21 @@ export function PromotePrompt({projectId,promptName,disabled,+ variant,}: {promptId: string;projectId: string;promptName: string;disabled: boolean;+ variant?: "ghost" | "outline";}) {- const [isPromoted, setIsPromoted] = useState(false);const utils = api.useUtils();const posthog = usePostHog();-+ const [isOpen, setIsOpen] = useState(false);const hasAccess = useHasAccess({ projectId, scope: "prompts:CUD" });const mutPromotePrompt = api.prompts.promote.useMutation({onSuccess: () => {- setIsPromoted(true);void utils.prompts.invalidate();},});@@ -39,9 +39,19 @@ export function PromotePrompt({}return (- <Popover key={promptId}>+ <Popover+ key={promptId}+ open={isOpen}+ onOpenChange={() => setIsOpen(!isOpen)}+ ><PopoverTrigger asChild>- <Button variant="ghost" size="xs" disabled={disabled}>+ <Button+ variant={variant ?? "ghost"}+ size={variant ? "icon" : "xs"}+ disabled={disabled}+ aria-label="Promote Prompt to production"+ title="Promote Prompt to production"+ ><PlayIcon className="h-4 w-4" /></Button></PopoverTrigger>@@ -59,13 +69,14 @@ export function PromotePrompt({<Buttontype="button"variant="destructive"- loading={mutPromotePrompt.isLoading || isPromoted}+ loading={mutPromotePrompt.isLoading}onClick={() => {void mutPromotePrompt.mutateAsync({promptId,projectId,});posthog.capture("prompt:promote");+ setIsOpen(false);}}>Promote to productiondiff --git a/src/features/prompts/components/prompt-detail.tsx b/src/features/prompts/components/prompt-detail.tsxindex 2820f95dd4..219cb40452 100644--- a/src/features/prompts/components/prompt-detail.tsx+++ b/src/features/prompts/components/prompt-detail.tsx@@ -9,77 +9,113 @@ import { api } from "@/src/utils/api";import { extractVariables } from "@/src/utils/string";import { type Prompt } from "@prisma/client";import { Pencil } from "lucide-react";+import { PromptHistoryNode } from "./prompt-history";+import { PromotePrompt } from "@/src/features/prompts/components/promote-prompt";+import { ScrollArea } from "@radix-ui/react-scroll-area";+import { useQueryParam, NumberParam } from "use-query-params";import router from "next/router";export type PromptDetailProps = {projectId: string;- promptId: string;+ promptName: string;};export const PromptDetail = (props: PromptDetailProps) => {- const prompt = api.prompts.byId.useQuery({- id: props.promptId,+ const [currentPromptVersion, setCurrentPromptVersion] = useQueryParam(+ "version",+ NumberParam,+ );+ const promptHistory = api.prompts.allVersions.useQuery({+ name: props.promptName,projectId: props.projectId,});+ const prompt = currentPromptVersion+ ? promptHistory.data?.find(+ (prompt) => prompt.version === currentPromptVersion,+ )+ : promptHistory.data?.[0];+ const extractedVariables = prompt ? extractVariables(prompt.prompt) : [];- const extractedVariables = prompt.data- ? extractVariables(prompt.data.prompt)- : [];-- if (!prompt.data) {+ if (!promptHistory.data || !prompt) {return <div>Loading...</div>;}return (- <div className="flex flex-col overflow-hidden xl:container md:h-[calc(100vh-100px)] xl:h-[calc(100vh-40px)]">- <Header- title={`${prompt.data.name} (v${prompt.data.version})`}- status={prompt.data.isActive ? "production" : "disabled"}- breadcrumb={[- {- name: "Prompts",- href: `/project/${props.projectId}/prompts/`,- },- { name: `${prompt.data.name} (v${prompt.data.version})` },- ]}- actionButtons={- <>- <CreatePromptDialog- projectId={props.projectId}- title="Update Prompt"- subtitle="We do not update prompts, instead we create a new version of the prompt."- promptName={prompt.data.name}- promptText={prompt.data.prompt}- >- <Button variant="outline" size="icon">- <Pencil className="h-5 w-5" />- </Button>- </CreatePromptDialog>- <DetailPageNav- key="nav"- currentId={props.promptId}- path={(id) =>- `/project/${router.query.projectId as string}/prompts/${id}`- }- listKey="prompts"- />- </>- }- />-- <CodeView content={prompt.data.prompt} title="Prompt" />- <div className="mx-auto mt-5 w-full rounded-lg border text-base leading-7 text-gray-700">- <div className="border-b px-3 py-1 text-xs font-medium">Variables</div>- <div className="flex flex-wrap gap-2 p-3">- {extractedVariables.length > 0 ? (- extractedVariables.map((variable) => (- <Badge key={variable} variant="outline">- {variable}- </Badge>- ))- ) : (- <span className="text-xs">No variables</span>- )}+ <div className="flex flex-col xl:container md:h-[calc(100vh-2rem)]">+ <div className="grid grid-cols-3 gap-4">+ <div className="col-span-3">+ <Header+ title={prompt.name}+ breadcrumb={[+ {+ name: "Prompts",+ href: `/project/${props.projectId}/prompts/`,+ },+ {+ name: prompt.name,+ href: `/project/${props.projectId}/prompts/${prompt.name}`,+ },+ { name: `Version ${prompt.version}` },+ ]}+ actionButtons={+ <>+ <PromotePrompt+ projectId={props.projectId}+ promptId={prompt.id}+ promptName={prompt.name}+ disabled={prompt.isActive}+ variant="outline"+ />+ <CreatePromptDialog+ projectId={props.projectId}+ title="Update Prompt"+ subtitle="We do not update prompts, instead we create a new version of the prompt."+ promptName={prompt.name}+ promptText={prompt.prompt}+ >+ <Button variant="outline" size="icon">+ <Pencil className="h-5 w-5" />+ </Button>+ </CreatePromptDialog>+ <DetailPageNav+ key="nav"+ currentId={prompt.name}+ path={(name) => `/project/${props.projectId}/prompts/${name}`}+ listKey="prompts"+ />+ </>+ }+ />+ </div>+ <div className="col-span-2 md:h-full">+ <CodeView content={prompt.prompt} title="Prompt" />+ <div className="mx-auto mt-5 w-full rounded-lg border text-base leading-7 text-gray-700">+ <div className="border-b px-3 py-1 text-xs font-medium">+ Variables+ </div>+ <div className="flex flex-wrap gap-2 p-3">+ {extractedVariables.length > 0 ? (+ extractedVariables.map((variable) => (+ <Badge key={variable} variant="outline">+ {variable}+ </Badge>+ ))+ ) : (+ <span className="text-xs">No variables</span>+ )}+ </div>+ </div>+ </div>+ <div className="flex h-screen flex-col">+ <div className="text-m px-3 font-medium">+ <ScrollArea className="flex border-l pl-2">+ <PromptHistoryNode+ prompts={promptHistory.data}+ currentPromptVersion={prompt.version}+ setCurrentPromptVersion={setCurrentPromptVersion}+ />+ </ScrollArea>+ </div></div></div></div>diff --git a/src/features/prompts/components/prompt-history.tsx b/src/features/prompts/components/prompt-history.tsxnew file mode 100644index 0000000000..83d348fc89--- /dev/null+++ b/src/features/prompts/components/prompt-history.tsx@@ -0,0 +1,65 @@+import { StatusBadge } from "@/src/components/layouts/status-badge";+import { type RouterOutputs } from "@/src/utils/api";+import { type NextRouter, useRouter } from "next/router";++const PromptHistoryTraceNode = (props: {+ index: number;+ prompt: RouterOutputs["prompts"]["allVersions"][number];+ currentPromptVersion: number | undefined;+ setCurrentPromptVersion: (version: number | undefined) => void;+ router: NextRouter;+ projectId: string;+}) => (+ <div+ className={`group mb-2 flex cursor-pointer flex-col gap-1 rounded-sm p-2 hover:bg-gray-50 ${+ props.currentPromptVersion === props.prompt.version ? "bg-gray-100" : ""+ }`}+ onClick={() => {+ props.index === 0+ ? props.setCurrentPromptVersion(undefined)+ : props.setCurrentPromptVersion(props.prompt.version);+ }}+ >+ <div className="flex items-center gap-2">+ <span className="rounded-sm bg-gray-200 p-1 text-xs">+ Version {props.prompt.version}+ </span>+ {props.prompt.isActive ? <StatusBadge type={"production"} /> : null}+ </div>++ <div className="flex gap-2">+ <span className="text-xs text-gray-500">+ {props.prompt.createdAt.toLocaleString()}+ </span>+ </div>+ <div className="flex gap-2">+ <span className="text-xs text-gray-500">+ by {props.prompt.creator || props.prompt.createdBy}+ </span>+ </div>+ </div>+);++export const PromptHistoryNode = (props: {+ prompts: RouterOutputs["prompts"]["allVersions"];+ currentPromptVersion: number | undefined;+ setCurrentPromptVersion: (id: number | undefined) => void;+}) => {+ const router = useRouter();+ const projectId = router.query.projectId as string;+ return (+ <div className="flex-1">+ {props.prompts.map((prompt, index) => (+ <PromptHistoryTraceNode+ key={prompt.id}+ index={index}+ prompt={prompt}+ currentPromptVersion={props.currentPromptVersion}+ setCurrentPromptVersion={props.setCurrentPromptVersion}+ router={router}+ projectId={projectId}+ />+ ))}+ </div>+ );+};diff --git a/src/features/prompts/components/prompts-table.tsx b/src/features/prompts/components/prompts-table.tsxindex e47bf0390b..1d5aacc000 100644--- a/src/features/prompts/components/prompts-table.tsx+++ b/src/features/prompts/components/prompts-table.tsx@@ -1,11 +1,9 @@-import { StatusBadge } from "@/src/components/layouts/status-badge";import { DataTable } from "@/src/components/table/data-table";import TableLink from "@/src/components/table/table-link";import { type LangfuseColumnDef } from "@/src/components/table/types";import { Button } from "@/src/components/ui/button";import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";import { CreatePromptDialog } from "@/src/features/prompts/components/new-prompt-button";-import { PromotePrompt } from "@/src/features/prompts/components/promote-prompt";import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";import { api } from "@/src/utils/api";@@ -14,12 +12,11 @@ import { LockIcon, PlusIcon } from "lucide-react";import { useEffect } from "react";type RowData = {- id: string;name: string;version: number;- isActive: boolean;- createdBy: string;+ id: string;createdAt: Date;+ isActive: boolean;};export function PromptTable(props: { projectId: string }) {@@ -28,7 +25,6 @@ export function PromptTable(props: { projectId: string }) {const prompts = api.prompts.all.useQuery({projectId: props.projectId,});-const hasCUDAccess = useHasAccess({projectId: props.projectId,scope: "prompts:CUD",@@ -38,7 +34,7 @@ export function PromptTable(props: { projectId: string }) {if (prompts.isSuccess) {setDetailPageList("prompts",- prompts.data.map((t) => t.id),+ prompts.data.map((t) => t.name),);}// eslint-disable-next-line react-hooks/exhaustive-deps@@ -46,84 +42,35 @@ export function PromptTable(props: { projectId: string }) {const columns: LangfuseColumnDef<RowData>[] = [{- accessorKey: "isActive",- header: "Status",- cell: ({ row }) => {- const isActive = row.getValue("isActive");- return isActive ? (- <StatusBadge type="production" className="h-6 w-24" />- ) : (- <StatusBadge type="disabled" className="h-6 w-24" />- );- },- },- {- accessorKey: "id",- header: "ID",+ accessorKey: "name",+ header: "Name",cell: ({ row }) => {- const value = row.getValue("id");- return value && typeof value === "string" ? (+ const name: string = row.getValue("name");+ return name && typeof name === "string" ? (<TableLink- path={`/project/${props.projectId}/prompts/${value}`}- value={value}+ path={`/project/${props.projectId}/prompts/${name}`}+ value={name}+ truncateAt={30}/>) : undefined;},},- {- accessorKey: "name",- header: "Name",- cell: ({ row }) => {- const name = row.getValue("name");- return name;- },- },{accessorKey: "version",- header: "Version",+ header: "Latest Version",cell: ({ row }) => {const version = row.getValue("version");return version;},},- {- accessorKey: "createdBy",- header: "Created By",- cell: ({ row }) => {- const createdBy = row.getValue("createdBy");- return createdBy;- },- },{accessorKey: "createdAt",- header: "Created At",+ header: "Latest Version Created At",cell: ({ row }) => {const createdAt: Date = row.getValue("createdAt");return createdAt.toLocaleString();},},- {- accessorKey: "action",- header: "Action",- cell: ({ row }) => {- const promptId = row.getValue("id");- const promptName = row.getValue("name");- const isActive = row.getValue("isActive");- return promptId &&- typeof promptId === "string" &&- isActive !== undefined &&- typeof isActive === "boolean" &&- promptName &&- typeof promptName === "string" ? (- <PromotePrompt- promptId={promptId}- projectId={props.projectId}- promptName={promptName}- disabled={isActive}- />- ) : undefined;- },- },];const convertToTableRow = (@@ -133,9 +80,8 @@ export function PromptTable(props: { projectId: string }) {id: item.id,name: item.name,version: item.version,- isActive: item.isActive,- createdBy: item.createdBy,createdAt: item.createdAt,+ isActive: item.isActive,};};@@ -160,7 +106,12 @@ export function PromptTable(props: { projectId: string }) {}/><CreatePromptDialog projectId={props.projectId} title="Create Prompt">- <Button variant="secondary" className="mt-4" disabled={!hasCUDAccess}>+ <Button+ variant="secondary"+ className="mt-4"+ disabled={!hasCUDAccess}+ aria-label="Promote Prompt to Production"+ >{hasCUDAccess ? (<PlusIcon className="-ml-0.5 mr-1.5" aria-hidden="true" />) : (diff --git a/src/features/prompts/server/prompt-router.ts b/src/features/prompts/server/prompt-router.tsindex cfc7e5d207..d96a1f8039 100644--- a/src/features/prompts/server/prompt-router.ts+++ b/src/features/prompts/server/prompt-router.ts@@ -5,7 +5,7 @@ import {protectedProjectProcedure,} from "@/src/server/api/trpc";import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";-import { type PrismaClient } from "@prisma/client";+import { type Prompt, type PrismaClient } from "@prisma/client";export const CreatePrompt = z.object({projectId: z.string(),@@ -27,12 +27,18 @@ export const promptRouter = createTRPCRouter({projectId: input.projectId,scope: "prompts:read",});- return ctx.prisma.prompt.findMany({- where: {- projectId: input.projectId,- },- orderBy: [{ name: "asc" }, { version: "desc" }],- });+ const prompts = await ctx.prisma.$queryRaw<Array<Prompt>>`+ SELECT id, name, version, project_id as "projectId", prompt, updated_at as "updatedAt", created_at AS "createdAt", is_active AS "isActive"+ FROM prompts+ WHERE (name, version) IN (+ SELECT name, MAX(version)+ FROM prompts+ WHERE "project_id" = ${input.projectId}+ GROUP BY name+ )+ AND "project_id" = ${input.projectId}+ ORDER BY name ASC`;+ return prompts;}),byId: protectedProjectProcedure.input(@@ -93,22 +99,15 @@ export const promptRouter = createTRPCRouter({},});- const latestActivePrompt = await ctx.prisma.prompt.findMany({+ const latestActivePrompt = await ctx.prisma.prompt.findFirst({where: {projectId: input.projectId,name: toBePromotedPrompt.name,isActive: true,},orderBy: [{ version: "desc" }],- take: 1,});- if (latestActivePrompt.length > 1) {- throw new Error(- `Expected exactly zero or one active prompt of name '${toBePromotedPrompt.name}', got ${latestActivePrompt.length}`,- );- }-const toBeExecuted = [ctx.prisma.prompt.update({where: {@@ -119,11 +118,11 @@ export const promptRouter = createTRPCRouter({},}),];- if (latestActivePrompt.length === 1)+ if (latestActivePrompt)toBeExecuted.push(ctx.prisma.prompt.update({where: {- id: latestActivePrompt[0]?.id,+ id: latestActivePrompt.id,},data: {isActive: false,@@ -136,6 +135,53 @@ export const promptRouter = createTRPCRouter({throw e;}}),+ allVersions: protectedProjectProcedure+ .input(z.object({ projectId: z.string(), name: z.string() }))+ .query(async ({ input, ctx }) => {+ throwIfNoAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "prompts:read",+ });+ const prompts = await ctx.prisma.prompt.findMany({+ where: {+ projectId: input.projectId,+ name: input.name,+ },+ orderBy: [{ version: "desc" }],+ });+ const users = await ctx.prisma.user.findMany({+ select: {+ // never select passwords as they should never be returned to the FE+ id: true,+ name: true,+ email: true,+ },+ where: {+ memberships: {+ some: {+ projectId: input.projectId,+ },+ },+ },+ });++ const joinedPromptAndUsers = prompts.map((p) => {+ const user = users.find((u) => u.id === p.createdBy);+ if (!user && p.createdBy !== "API") {+ return { ...p, creator: "API" };+ }+ if (!user) {+ console.log(`User not found for promptId ${p.id}`);+ throw new Error("User not found");+ }+ return {+ ...p,+ creator: user.name,+ };+ });+ return joinedPromptAndUsers;+ }),});export const createPrompt = async ({@@ -159,7 +205,6 @@ export const createPrompt = async ({name: name,},orderBy: [{ version: "desc" }],- take: 1,});const latestActivePrompt = await prisma.prompt.findFirst({@@ -169,7 +214,6 @@ export const createPrompt = async ({isActive: true,},orderBy: [{ version: "desc" }],- take: 1,});const create = [diff --git a/src/features/public-api/components/ApiKeyList.tsx b/src/features/public-api/components/ApiKeyList.tsxindex 0f7138d5c6..10bcf8df0a 100644--- a/src/features/public-api/components/ApiKeyList.tsx+++ b/src/features/public-api/components/ApiKeyList.tsx@@ -115,7 +115,7 @@ function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {return (<Dialog open={open} onOpenChange={setOpen}><DialogTrigger asChild>- <Button variant="ghost" size="xs">+ <Button variant="ghost" size="icon"><TrashIcon className="h-4 w-4" /></Button></DialogTrigger>diff --git a/src/features/rbac/components/ProjectMembersTable.tsx b/src/features/rbac/components/ProjectMembersTable.tsxindex 84cc6df781..f3a5252ee8 100644--- a/src/features/rbac/components/ProjectMembersTable.tsx+++ b/src/features/rbac/components/ProjectMembersTable.tsx@@ -75,7 +75,7 @@ export function ProjectMembersTable({ projectId }: { projectId: string }) {<TableCell><Buttonvariant="ghost"- size="xs"+ size="icon"loading={mutDeleteMembership.isLoading}onClick={() => {mutDeleteMembership.mutate({@@ -120,7 +120,7 @@ export function ProjectMembersTable({ projectId }: { projectId: string }) {<TableCell><Buttonvariant="ghost"- size="xs"+ size="icon"loading={mutDeleteInvitation.isLoading}onClick={() => {mutDeleteInvitation.mutate({diff --git a/src/pages/project/[projectId]/prompts/[promptId].tsx b/src/pages/project/[projectId]/prompts/[promptName]/index.tsxsimilarity index 66%rename from src/pages/project/[projectId]/prompts/[promptId].tsxrename to src/pages/project/[projectId]/prompts/[promptName]/index.tsxindex d9139a6522..b6558e289c 100644--- a/src/pages/project/[projectId]/prompts/[promptId].tsx+++ b/src/pages/project/[projectId]/prompts/[promptName]/index.tsx@@ -3,8 +3,8 @@ import { useRouter } from "next/router";export default function PromptDetailPage() {const router = useRouter();- const promptId = router.query.promptId as string;const projectId = router.query.projectId as string;+ const promptName = router.query.promptName as string;- return <PromptDetail projectId={projectId} promptId={promptId} />;+ return <PromptDetail projectId={projectId} promptName={promptName} />;}diff --git a/src/pages/project/[projectId]/prompts/index.tsx b/src/pages/project/[projectId]/prompts/index.tsxindex 2b43ddd6d9..75d55f7264 100644--- a/src/pages/project/[projectId]/prompts/index.tsx+++ b/src/pages/project/[projectId]/prompts/index.tsx@@ -7,7 +7,7 @@ export default function Prompts() {const projectId = router.query.projectId as string;return (- <div>+ <div className="xl:container"><Headertitle="Prompts"help={{