🪢 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 ui for tags on traces (#879)
Richard Krümmeleefdf60e3197
diff --git a/src/components/table/data-table.tsx b/src/components/table/data-table.tsxindex 421e072525..6016deaf81 100644--- a/src/components/table/data-table.tsx+++ b/src/components/table/data-table.tsx@@ -122,10 +122,14 @@ export function DataTable<TData extends object, TValue>({}if (orderBy?.column === header.column.columnDef.id) {- setOrderBy({- column: header.column.columnDef.id,- order: orderBy.order === "ASC" ? "DESC" : "ASC",- });+ if (orderBy.order === "DESC") {+ setOrderBy({+ column: header.column.columnDef.id,+ order: "ASC",+ });+ } else {+ setOrderBy(null);+ }} else {setOrderBy({column: header.column.columnDef.id,diff --git a/src/components/table/use-cases/traces.tsx b/src/components/table/use-cases/traces.tsxindex bee6d7ea77..c9969d430f 100644--- a/src/components/table/use-cases/traces.tsx+++ b/src/components/table/use-cases/traces.tsx@@ -6,6 +6,7 @@ import { TraceTableMultiSelectAction } from "@/src/components/table/data-table-mimport { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import TableLink from "@/src/components/table/table-link";import { type LangfuseColumnDef } from "@/src/components/table/types";+import { TagTracePopver } from "@/src/features/tag/components/TagTracePopver";import { TokenUsageBadge } from "@/src/components/token-usage-badge";import { Checkbox } from "@/src/components/ui/checkbox";import { JSONView } from "@/src/components/ui/code";@@ -135,7 +136,6 @@ export default function TracesTable({},},);-const convertToTableRow = (trace: RouterOutput["traces"]["all"]["traces"][0],): TracesTableRow => {@@ -198,7 +198,6 @@ export default function TracesTable({cell: ({ row }) => {const bookmarked = row.getValue("bookmarked");const traceId = row.getValue("id");-return typeof traceId === "string" &&typeof bookmarked === "boolean" ? (<StarTraceToggle@@ -364,6 +363,21 @@ export default function TracesTable({accessorKey: "tags",id: "tags",header: "Tags",+ cell: ({ row }) => {+ const tags: string[] = row.getValue("tags");+ const traceId: string = row.getValue("id");+ const filterOptionTags = traceFilterOptions.data?.tags ?? [];+ const allTags = filterOptionTags.map((t) => t.value);+ return (+ <TagTracePopver+ tags={tags}+ availableTags={allTags}+ projectId={projectId}+ traceId={traceId}+ tracesFilter={tracesAllQueryFilter}+ />+ );+ },enableHiding: true,},{diff --git a/src/components/trace/index.tsx b/src/components/trace/index.tsxindex 63535d7405..73b210f999 100644--- a/src/components/trace/index.tsx+++ b/src/components/trace/index.tsx@@ -16,6 +16,7 @@ import { DeleteTrace } from "@/src/components/delete-trace";import { StarTraceDetailsToggle } from "@/src/components/star-toggle";import Link from "next/link";import { NoAccessError } from "@/src/components/no-access";+import { TagTraceDetailsPopover } from "@/src/features/tag/components/TagTraceDetailsPopover";import useLocalStorage from "@/src/components/useLocalStorage";import { Toggle } from "@/src/components/ui/toggle";import { Award, ChevronsDownUp, ChevronsUpDown } from "lucide-react";@@ -114,6 +115,24 @@ export function TracePage({ traceId }: { traceId: string }) {},},);++ const traceFilterOptions = api.traces.filterOptions.useQuery(+ {+ projectId: trace.data?.projectId ?? "",+ },+ {+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ enabled: !!trace.data?.projectId && trace.isSuccess,+ },+ );++ const filterOptionTags = traceFilterOptions.data?.tags ?? [];+ const allTags = filterOptionTags.map((t) => t.value);+const totalCost: number | undefined = trace.data?.observations.reduce((prev: number | undefined, curr: ObservationReturnType) => {if (!curr.price) return prev;@@ -122,10 +141,8 @@ export function TracePage({ traceId }: { traceId: string }) {},undefined,);-if (trace.error?.data?.code === "UNAUTHORIZED") return <NoAccessError />;if (!trace.data) return <div>loading...</div>;-return (<div className="flex flex-col overflow-hidden xl:container md:h-[calc(100vh-2rem)]"><Header@@ -187,6 +204,17 @@ export function TracePage({ traceId }: { traceId: string }) {<Badge variant="outline">Total cost: {usdFormatter(totalCost)}</Badge>) : undefined}</div>+ <div className="mt-5 rounded-lg border bg-card font-semibold text-card-foreground shadow-sm">+ <div className="flex flex-row items-center gap-3 p-2.5">+ Tags+ <TagTraceDetailsPopover+ tags={trace.data.tags}+ availableTags={allTags}+ traceId={trace.data.id}+ projectId={trace.data.projectId}+ />+ </div>+ </div><div className="mt-5 flex-1 overflow-hidden border-t pt-5"><Tracekey={trace.data.id}diff --git a/src/features/rbac/constants/roleAccessRights.ts b/src/features/rbac/constants/roleAccessRights.tsindex e9e95a6e67..e801fdc5a8 100644--- a/src/features/rbac/constants/roleAccessRights.ts+++ b/src/features/rbac/constants/roleAccessRights.ts@@ -11,6 +11,7 @@ const scopes = ["objects:publish","objects:bookmark",+ "objects:tag","traces:delete",@@ -39,6 +40,7 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {"apiKeys:delete","objects:publish","objects:bookmark",+ "objects:tag","traces:delete","scores:CUD","project:delete",@@ -58,6 +60,7 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {"apiKeys:delete","objects:publish","objects:bookmark",+ "objects:tag","traces:delete","scores:CUD","datasets:CUD",@@ -68,6 +71,7 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {"members:read","objects:publish","objects:bookmark",+ "objects:tag","scores:CUD","datasets:CUD","prompts:CUD",diff --git a/src/features/tag/components/TagButton.tsx b/src/features/tag/components/TagButton.tsxnew file mode 100644index 0000000000..151d9138d4--- /dev/null+++ b/src/features/tag/components/TagButton.tsx@@ -0,0 +1,16 @@+import { Button } from "@/src/components/ui/button";+import React from "react";++export const TagButton: React.FC<{ tag: string; loading: boolean }> =+ React.memo(({ tag, loading }) => (+ <Button+ key={tag}+ variant="secondary"+ size="xs"+ className="text-xs font-semibold hover:bg-white"+ loading={loading}+ >+ {tag}+ </Button>+ ));+TagButton.displayName = "TagButton";diff --git a/src/features/tag/components/TagCommandItem.tsx b/src/features/tag/components/TagCommandItem.tsxnew file mode 100644index 0000000000..c95bf2469d--- /dev/null+++ b/src/features/tag/components/TagCommandItem.tsx@@ -0,0 +1,38 @@+import { CommandItem } from "@/src/components/ui/command";+import { cn } from "@/src/utils/tailwind";+import { Check } from "lucide-react";+import { Button } from "@/src/components/ui/button";++type TagCommandItemProps = {+ value: string;+ selectedTags: string[];+ setSelectedTags: (value: string[]) => void;+};++const TagCommandItem = ({+ value,+ selectedTags,+ setSelectedTags,+}: TagCommandItemProps) => {+ return (+ <CommandItem+ key={value}+ onSelect={() => {+ setSelectedTags([...selectedTags, value]);+ }}+ >+ <div+ className={cn(+ "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary opacity-50 [&_svg]:invisible",+ )}+ >+ <Check className={cn("h-4 w-4")} />+ </div>+ <Button variant="secondary" size="xs">+ {value}+ </Button>+ </CommandItem>+ );+};++export default TagCommandItem;\ No newline at end of filediff --git a/src/features/tag/components/TagCreateItem.tsx b/src/features/tag/components/TagCreateItem.tsxnew file mode 100644index 0000000000..0eac045750--- /dev/null+++ b/src/features/tag/components/TagCreateItem.tsx@@ -0,0 +1,37 @@+import React from "react";+import { cn } from "@/src/utils/tailwind";+import { CommandItem } from "cmdk";++type TagItemCreateProps = {+ inputValue: string;+ options: string[];+ onSelect: () => void;+};++const TagItemCreate = ({+ inputValue,+ options,+ onSelect,+}: TagItemCreateProps) => {+ const hasNoOption = !options+ .map((value) => value.toLowerCase())+ .includes(inputValue.toLowerCase());++ const render = inputValue !== "" && hasNoOption;++ if (!render) return null;++ return (+ <CommandItem+ key={inputValue}+ value={inputValue}+ className="flex cursor-pointer items-center rounded-sm px-1 py-2 text-muted-foreground hover:bg-secondary/80"+ onSelect={onSelect}+ >+ <div className={cn("mr-2 h-4 w-4")} />+ Create new tag: "{inputValue}"+ </CommandItem>+ );+};++export default TagItemCreate;diff --git a/src/features/tag/components/TagInput.tsx b/src/features/tag/components/TagInput.tsxnew file mode 100644index 0000000000..2f9c7f3961--- /dev/null+++ b/src/features/tag/components/TagInput.tsx@@ -0,0 +1,49 @@+import React from "react";+import { cn } from "@/src/utils/tailwind";+import { X } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { Command as CommandPrimitive } from "cmdk";++type TagInputProps = React.ComponentPropsWithoutRef<+ typeof CommandPrimitive.Input+> & {+ selectedTags: string[];+ setSelectedTags: (tags: string[]) => void;+};++export const TagInput = React.forwardRef<+ React.ElementRef<typeof CommandPrimitive.Input>,+ TagInputProps+>(({ className, selectedTags, setSelectedTags, ...props }, ref) => (+ <div+ className="flex flex-wrap items-center overflow-auto rounded-lg border px-2 pt-2"+ cmdk-input-wrapper=""+ >+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ {selectedTags.map((tag: string) => (+ <Button+ key={tag}+ variant="secondary"+ size="xs"+ onClick={() => {+ const newTags = selectedTags.filter((t) => t !== tag);+ setSelectedTags(newTags);+ }}+ >+ {tag}+ <X className="ml-1 h-3 w-3" />+ </Button>+ ))}+ </div>+ <CommandPrimitive.Input+ ref={ref}+ className={cn(+ "flex h-11 w-full rounded-md border-transparent bg-transparent px-1 text-sm outline-none placeholder:text-slate-500 focus:border-0 focus:border-none focus:border-transparent focus:ring-0 disabled:cursor-not-allowed disabled:opacity-50 dark:placeholder:text-slate-400 ",+ className,+ )}+ {...props}+ />+ </div>+));++TagInput.displayName = CommandPrimitive.Input.displayName;diff --git a/src/features/tag/components/TagList.tsx b/src/features/tag/components/TagList.tsxnew file mode 100644index 0000000000..dcee96090e--- /dev/null+++ b/src/features/tag/components/TagList.tsx@@ -0,0 +1,25 @@+import { Button } from "@/src/components/ui/button";+import { TagButton } from "@/src/features/tag/components/TagButton";++type TagListProps = {+ selectedTags: string[];+ isLoading: boolean;+};++const TagList = ({ selectedTags, isLoading }: TagListProps) => {+ return selectedTags.length > 0 ? (+ selectedTags.map((tag) => (+ <TagButton key={tag} tag={tag} loading={isLoading} />+ ))+ ) : (+ <Button+ variant="outline"+ size="xs"+ className="text-xs font-bold opacity-0 hover:bg-white hover:opacity-100"+ >+ Add tag+ </Button>+ );+};++export default TagList;diff --git a/src/features/tag/components/TagMananger.tsx b/src/features/tag/components/TagMananger.tsxnew file mode 100644index 0000000000..6ee0b1c049--- /dev/null+++ b/src/features/tag/components/TagMananger.tsx@@ -0,0 +1,88 @@+import TagCommandItem from "@/src/features/tag/components/TagCommandItem";+import TagCreateItem from "@/src/features/tag/components/TagCreateItem";+import { TagInput } from "@/src/features/tag/components/TagInput";+import TagList from "@/src/features/tag/components/TagList";+import useTagManager from "@/src/features/tag/hooks/useTagManager";+import {+ Popover,+ PopoverTrigger,+ PopoverContent,+} from "@/src/components/ui/popover";+import { Command, CommandList, CommandGroup } from "cmdk";++type TagManagerProps = {+ tags: string[];+ allTags: string[];+ hasAccess: boolean;+ isLoading: boolean;+ mutateTags: (value: string[]) => void;+};++const TagManager = ({+ tags,+ allTags,+ hasAccess,+ isLoading,+ mutateTags,+}: TagManagerProps) => {+ const {+ selectedTags,+ inputValue,+ availableTags,+ handleItemCreate,+ setInputValue,+ setSelectedTags,+ } = useTagManager({ initialTags: tags, allTags });++ const handlePopoverChange = (open: boolean) => {+ if (!open && selectedTags !== tags) {+ setInputValue("");+ mutateTags(selectedTags);+ }+ };++ if (!hasAccess) {+ return <TagList selectedTags={selectedTags} isLoading={isLoading} />;+ }++ return (+ <Popover onOpenChange={(open) => handlePopoverChange(open)}>+ <PopoverTrigger className="select-none" asChild>+ <div className="flex flex-wrap gap-x-2 gap-y-1">+ <TagList selectedTags={selectedTags} isLoading={isLoading} />+ </div>+ </PopoverTrigger>+ <PopoverContent>+ <Command>+ <TagInput+ value={inputValue}+ onValueChange={setInputValue}+ selectedTags={selectedTags}+ setSelectedTags={setSelectedTags}+ />+ <CommandList+ className={availableTags.length > 0 ? "mt-2" : undefined}+ >+ <CommandGroup>+ {availableTags.map((value: string) => (+ <TagCommandItem+ key={value}+ value={value}+ selectedTags={selectedTags}+ setSelectedTags={setSelectedTags}+ />+ ))}+ <TagCreateItem+ onSelect={handleItemCreate}+ inputValue={inputValue}+ options={allTags}+ />+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ );+};++export default TagManager;diff --git a/src/features/tag/components/TagTraceDetailsPopover.tsx b/src/features/tag/components/TagTraceDetailsPopover.tsxnew file mode 100644index 0000000000..cc3da8d9bc--- /dev/null+++ b/src/features/tag/components/TagTraceDetailsPopover.tsx@@ -0,0 +1,74 @@+import React, { useState } from "react";+import { api } from "@/src/utils/api";+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { type RouterOutput } from "@/src/utils/types";+import TagManager from "@/src/features/tag/components/TagMananger";++type TagTraceDetailsPopoverProps = {+ tags: string[];+ availableTags: string[];+ projectId: string;+ traceId: string;+};++export function TagTraceDetailsPopover({+ tags,+ availableTags,+ projectId,+ traceId,+}: TagTraceDetailsPopoverProps) {+ const [isLoading, setIsLoading] = useState(false);+ const hasAccess = useHasAccess({ projectId, scope: "objects:tag" });++ const utils = api.useUtils();+ const mutTags = api.traces.updateTags.useMutation({+ onMutate: async () => {+ await utils.traces.byId.cancel();+ setIsLoading(true);+ // Snapshot the previous value+ const prev = utils.traces.byId.getData({ traceId });++ return { prev };+ },+ onError: (err, _newTags, context) => {+ setIsLoading(false);+ // Rollback to the previous value if mutation fails+ utils.traces.byId.setData({ traceId }, context?.prev);+ },+ onSettled: (data, error, { traceId, tags }) => {+ setIsLoading(false);+ utils.traces.byId.setData(+ { traceId },+ (oldQueryData: RouterOutput["traces"]["byId"] | undefined) => {+ return oldQueryData+ ? {+ ...oldQueryData,+ tags: tags,+ }+ : undefined;+ },+ );+ void utils.traces.all.invalidate();+ void utils.traces.byId.invalidate();+ void utils.traces.filterOptions.invalidate();+ },+ });++ function mutateTags(newTags: string[]) {+ void mutTags.mutateAsync({+ projectId,+ traceId,+ tags: newTags,+ });+ }++ return (+ <TagManager+ tags={tags}+ allTags={availableTags}+ hasAccess={hasAccess}+ isLoading={isLoading}+ mutateTags={mutateTags}+ />+ );+}diff --git a/src/features/tag/components/TagTracePopver.tsx b/src/features/tag/components/TagTracePopver.tsxnew file mode 100644index 0000000000..1b14ffb8ff--- /dev/null+++ b/src/features/tag/components/TagTracePopver.tsx@@ -0,0 +1,73 @@+import React, { useState } from "react";+import { api } from "@/src/utils/api";+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import { type RouterOutput, type RouterInput } from "@/src/utils/types";+import TagManager from "@/src/features/tag/components/TagMananger";++type TagTracePopverProps = {+ tags: string[];+ availableTags: string[];+ projectId: string;+ traceId: string;+ tracesFilter: RouterInput["traces"]["all"];+};++export function TagTracePopver({+ tags,+ availableTags,+ projectId,+ traceId,+ tracesFilter,+}: TagTracePopverProps) {+ const [isLoading, setIsLoading] = useState(false);+ const hasAccess = useHasAccess({ projectId, scope: "objects:tag" });++ const utils = api.useUtils();+ const mutTags = api.traces.updateTags.useMutation({+ onMutate: async () => {+ await utils.traces.all.cancel();+ setIsLoading(true);+ const prevTrace = utils.traces.all.getData(tracesFilter);+ return { prevTrace };+ },+ onError: (err, _newTags, context) => {+ utils.traces.all.setData(tracesFilter, context?.prevTrace);+ console.log("error", err);+ setIsLoading(false);+ },+ onSettled: (data, error, { traceId, tags }) => {+ utils.traces.all.setData(+ tracesFilter,+ (oldQueryData: RouterOutput["traces"]["all"] | undefined) => {+ return oldQueryData+ ? {+ totalCount: oldQueryData.totalCount,+ traces: oldQueryData.traces.map((trace) => {+ return trace.id === traceId ? { ...trace, tags } : trace;+ }),+ }+ : { totalCount: undefined, traces: [] };+ },+ );+ setIsLoading(false);+ },+ });++ function mutateTags(newTags: string[]) {+ void mutTags.mutateAsync({+ projectId,+ traceId,+ tags: newTags,+ });+ }++ return (+ <TagManager+ tags={tags}+ allTags={availableTags}+ hasAccess={hasAccess}+ isLoading={isLoading}+ mutateTags={mutateTags}+ />+ );+}diff --git a/src/features/tag/hooks/useTagManager.tsx b/src/features/tag/hooks/useTagManager.tsxnew file mode 100644index 0000000000..54845c2765--- /dev/null+++ b/src/features/tag/hooks/useTagManager.tsx@@ -0,0 +1,32 @@+import { useState, useMemo } from "react";++type UseTagManagerProps = {+ initialTags: string[];+ allTags: string[];+};++function useTagManager({ initialTags, allTags }: UseTagManagerProps) {+ const [selectedTags, setSelectedTags] = useState(initialTags);+ const [inputValue, setInputValue] = useState("");++ const availableTags = useMemo(+ () => allTags.filter((value) => !selectedTags.includes(value)),+ [allTags, selectedTags],+ );+ const handleItemCreate = () => {+ setSelectedTags([...selectedTags, inputValue]);+ availableTags.push(inputValue);+ setInputValue("");+ };++ return {+ selectedTags,+ inputValue,+ availableTags,+ handleItemCreate,+ setInputValue,+ setSelectedTags,+ };+}++export default useTagManager;diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.tsindex 683c4992f7..8c35927054 100644--- a/src/server/api/routers/traces.ts+++ b/src/server/api/routers/traces.ts@@ -313,7 +313,6 @@ export const traceRouter = createTRPCRouter({bookmarked: input.bookmarked,},});-return trace;} catch (error) {console.error(error);@@ -374,6 +373,37 @@ export const traceRouter = createTRPCRouter({}}}),+ updateTags: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ traceId: z.string(),+ tags: z.array(z.string()),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "objects:tag",+ });+ try {+ const trace = await ctx.prisma.trace.update({+ where: {+ id: input.traceId,+ projectId: input.projectId,+ },+ data: {+ tags: {+ set: input.tags,+ },+ },+ });+ return trace;+ } catch (error) {+ console.error(error);+ }+ }),});function createTracesQuery(