🪢 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(score_configs): add archive functionality (#2340)
marliessophieddfc42f7393d
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsxindex 947929a2fe..ef7aefde0c 100644--- a/web/src/components/session/index.tsx+++ b/web/src/components/session/index.tsx@@ -13,7 +13,7 @@ import { api } from "@/src/utils/api";import { usdFormatter } from "@/src/utils/numbers";import Link from "next/link";import { useEffect, useState } from "react";-import { AnnotateButton } from "@/src/features/manual-scoring/components/AnnotateButton";+import { AnnotateDrawer } from "@/src/features/manual-scoring/components/AnnotateDrawer";import { Button } from "@/src/components/ui/button";// some projects have thousands of traces in a sessions, paginate to avoid rendering all at once@@ -125,7 +125,7 @@ export const SessionPage: React.FC<{<div className="mb-1 flex flex-wrap content-start items-start gap-1"><GroupedScoreBadges scores={trace.scores} /></div>- <AnnotateButton+ <AnnotateDrawerprojectId={projectId}traceId={trace.id}scores={trace.scores}diff --git a/web/src/components/table/use-cases/score-configs.tsx b/web/src/components/table/use-cases/score-configs.tsxindex 45083670af..1b77c35696 100644--- a/web/src/components/table/use-cases/score-configs.tsx+++ b/web/src/components/table/use-cases/score-configs.tsx@@ -10,6 +10,16 @@ import { type ScoreDataType, type Prisma } from "@langfuse/shared";import { IOTableCell } from "@/src/components/ui/CodeJsonViewer";import { NumberParam, useQueryParams, withDefault } from "use-query-params";import { isNumericDataType } from "@/src/features/manual-scoring/lib/helpers";+import { Archive } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import useLocalStorage from "@/src/components/useLocalStorage";type ScoreConfigTableRow = {id: string;@@ -23,6 +33,7 @@ type ScoreConfigTableRow = {categories?: Prisma.JsonValue | null;};description?: string | null;+ isArchived: boolean;};function getConfigRange(@@ -38,6 +49,17 @@ function getConfigRange(}export function ScoreConfigsTable({ projectId }: { projectId: string }) {+ const utils = api.useUtils();+ const capture = usePostHogClientCapture();+ const [emptySelectedConfigIds, setEmptySelectedConfigIds] = useLocalStorage<+ string[]+ >("emptySelectedConfigIds", []);++ const hasAccess = useHasAccess({+ projectId: projectId,+ scope: "scoreConfigs:CUD",+ });+const [paginationState, setPaginationState] = useQueryParams({pageIndex: withDefault(NumberParam, 0),pageSize: withDefault(NumberParam, 50),@@ -109,6 +131,73 @@ export function ScoreConfigsTable({ projectId }: { projectId: string }) {enableHiding: true,defaultHidden: true,},+ {+ accessorKey: "isArchived",+ id: "isArchived",+ header: "Status",+ enableHiding: true,+ cell: ({ row }) => {+ const { isArchived } = row.original;+ return isArchived ? "Archived" : "Active";+ },+ },+ {+ accessorKey: "action",+ header: "Action",+ enableHiding: true,+ cell: ({ row }) => {+ const { id: configId, isArchived, name } = row.original;+ const configMutation = api.scoreConfigs.update.useMutation({+ onSuccess: () => void utils.scoreConfigs.invalidate(),+ });++ return (+ <Popover key={configId}>+ <PopoverTrigger asChild>+ <Button+ variant="ghost"+ size="xs"+ disabled={!hasAccess}+ onClick={() => capture("score_configs:archive_form_open")}+ >+ <Archive className="h-4 w-4"></Archive>+ </Button>+ </PopoverTrigger>+ <PopoverContent>+ <h2 className="text-md mb-3 font-semibold">+ {isArchived ? "Restore config" : "Archive config"}+ </h2>+ <p className="mb-3 text-sm">+ Your config is currently{" "}+ {isArchived+ ? `archived. Restore if you want to use "${name}" in annotation again.`+ : `active. Archive if you no longer want to use "${name}" in annotation. Historic "${name}" scores will still be shown and can be deleted. You can restore your config at any point.`}+ </p>+ <div className="flex justify-end space-x-4">+ <Button+ type="button"+ variant={isArchived ? "default" : "destructive"}+ loading={configMutation.isLoading}+ onClick={() => {+ void configMutation.mutateAsync({+ projectId,+ id: configId,+ isArchived: !isArchived,+ });+ setEmptySelectedConfigIds(+ emptySelectedConfigIds.filter((id) => id !== configId),+ );+ capture("score_configs:archive_form_submit");+ }}+ >+ Confirm+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ );+ },+ },];const [columnVisibility, setColumnVisibility] =@@ -153,6 +242,7 @@ export function ScoreConfigsTable({ projectId }: { projectId: string }) {minValue: config.minValue,categories: config.categories,},+ isArchived: config.isArchived,})),}}diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsxindex 485e1e875a..84f2192fc7 100644--- a/web/src/components/trace/ObservationPreview.tsx+++ b/web/src/components/trace/ObservationPreview.tsx@@ -21,7 +21,7 @@ import { withDefault, StringParam, useQueryParam } from "use-query-params";import ScoresTable from "@/src/components/table/use-cases/scores";import { ScoresPreview } from "@/src/components/trace/ScoresPreview";import { JumpToPlaygroundButton } from "@/src/ee/features/playground/page/components/JumpToPlaygroundButton";-import { AnnotateButton } from "@/src/features/manual-scoring/components/AnnotateButton";+import { AnnotateDrawer } from "@/src/features/manual-scoring/components/AnnotateDrawer";export const ObservationPreview = (props: {observations: Array<ObservationReturnType>;@@ -154,7 +154,7 @@ export const ObservationPreview = (props: {</div></div><div className="flex flex-wrap gap-2">- <AnnotateButton+ <AnnotateDrawerprojectId={props.projectId}traceId={preloadedObservation.traceId}observationId={preloadedObservation.id}diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsxindex 38cc77ab55..23db8c38f5 100644--- a/web/src/components/trace/TracePreview.tsx+++ b/web/src/components/trace/TracePreview.tsx@@ -18,7 +18,7 @@ import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";import { withDefault, StringParam, useQueryParam } from "use-query-params";import ScoresTable from "@/src/components/table/use-cases/scores";import { ScoresPreview } from "@/src/components/trace/ScoresPreview";-import { AnnotateButton } from "@/src/features/manual-scoring/components/AnnotateButton";+import { AnnotateDrawer } from "@/src/features/manual-scoring/components/AnnotateDrawer";export const TracePreview = ({trace,@@ -95,7 +95,7 @@ export const TracePreview = ({</div></div><div className="flex flex-wrap gap-2">- <AnnotateButton+ <AnnotateDrawerprojectId={trace.projectId}traceId={trace.id}scores={scores}diff --git a/web/src/components/trace/lib/helpers.ts b/web/src/components/trace/lib/helpers.tsindex 6674bfffd7..438f34e564 100644--- a/web/src/components/trace/lib/helpers.ts+++ b/web/src/components/trace/lib/helpers.ts@@ -16,10 +16,15 @@ export function nestObservations(): NestedObservation[] {if (list.length === 0) return [];+ // Step 0: Sort the list by start time to ensure observations are in right order+ const sortedObservations = list.sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );+// Step 1: Create a map where the keys are object IDs, and the values are// the corresponding objects with an added 'children' property.const map = new Map<string, NestedObservation>();- for (const obj of list) {+ for (const obj of sortedObservations) {map.set(obj.id, { ...obj, children: [] });}diff --git a/web/src/features/manual-scoring/components/AnnotateButton.tsx b/web/src/features/manual-scoring/components/AnnotateDrawer.tsxsimilarity index 81%rename from web/src/features/manual-scoring/components/AnnotateButton.tsxrename to web/src/features/manual-scoring/components/AnnotateDrawer.tsxindex 1b64991597..46badf6555 100644--- a/web/src/features/manual-scoring/components/AnnotateButton.tsx+++ b/web/src/features/manual-scoring/components/AnnotateDrawer.tsx@@ -7,6 +7,7 @@ import {MessageCircle,X,SquarePen,+ Archive,} from "lucide-react";import {type ControllerRenderProps,@@ -63,6 +64,7 @@ import { CommandItem } from "@/src/components/ui/command";import { useRouter } from "next/router";import useLocalStorage from "@/src/components/useLocalStorage";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { cn } from "@/src/utils/tailwind";const AnnotationScoreDataSchema = z.object({name: z.string(),@@ -85,7 +87,7 @@ type ConfigCategory = {value: string;};-export function AnnotateButton({+export function AnnotateDrawer({traceId,scores,observationId,@@ -149,15 +151,21 @@ export function AnnotateButton({const updatedScoreIndex = fields.findIndex((field) => field.scoreId === id,);- update(updatedScoreIndex, {- name,- dataType,- configId: configId ?? undefined,- value: null,- scoreId: undefined,- stringValue: undefined,- comment: undefined,- });++ const config = configs.find((config) => config.id === configId);+ if (config && config.isArchived) {+ remove(updatedScoreIndex);+ } else {+ update(updatedScoreIndex, {+ name,+ dataType,+ configId: configId ?? undefined,+ value: null,+ scoreId: undefined,+ stringValue: undefined,+ comment: undefined,+ });+ }await Promise.all([utils.scores.invalidate(),@@ -457,13 +465,21 @@ export function AnnotateButton({items="empty scores"className="grid grid-cols-[auto,1fr,auto,auto] gap-2"onValueChange={handleOnCheckedChange}- options={configs.map((config) => ({- key: config.id,- value: config.name,- disabled: fields.some(- (field) => !!field.scoreId && field.configId === config.id,- ),- }))}+ options={configs+ .filter(+ (config) =>+ !config.isArchived ||+ fields.find((field) => field.configId === config.id),+ )+ .map((config) => ({+ key: config.id,+ value: config.name,+ disabled: fields.some(+ (field) =>+ !!field.scoreId && field.configId === config.id,+ ),+ isArchived: config.isArchived,+ }))}values={fields.filter((field) => !!field.configId).map((field) => ({@@ -513,7 +529,14 @@ export function AnnotateButton({isPresent(config.minValue) ? (<HoverCard><HoverCardTrigger asChild>- <span className="line-clamp-2 break-words text-xs font-medium underline decoration-muted-gray decoration-dashed underline-offset-2">+ <span+ className={cn(+ "line-clamp-2 break-words text-xs font-medium underline decoration-muted-gray decoration-dashed underline-offset-2",+ config.isArchived+ ? "text-foreground/40"+ : "",+ )}+ >{score.name}</span></HoverCardTrigger>@@ -523,7 +546,12 @@ export function AnnotateButton({</HoverCard>) : (<span- className="line-clamp-2 break-words text-xs font-medium"+ className={cn(+ "line-clamp-2 break-words text-xs font-medium",+ config.isArchived+ ? "text-foreground/40"+ : "",+ )}title={score.name}>{score.name}@@ -537,7 +565,10 @@ export function AnnotateButton({size="xs"title="Add or view score comment"className="h-full items-start px-0 pl-1 disabled:text-primary/50 disabled:opacity-100"- disabled={isScoreUnsaved(score.scoreId)}+ disabled={+ isScoreUnsaved(score.scoreId) ||+ (config.isArchived && !score.comment)+ }>{score.comment ? (<MessageCircleMore className="h-4 w-4" />@@ -589,7 +620,10 @@ export function AnnotateButton({type="button"size="sm"className="text-xs"- disabled={!field.value}+ disabled={+ !field.value ||+ config.isArchived+ }loading={mutUpdateScores.isLoading}@@ -653,7 +687,7 @@ export function AnnotateButton({</PopoverContent></Popover></div>- <div className="grid grid-cols-[11fr,1fr]">+ <div className="grid grid-cols-[11fr,1fr] items-center"><FormFieldcontrol={form.control}name={`scoreData.${index}.value`}@@ -666,6 +700,7 @@ export function AnnotateButton({value={field.value ?? undefined}type="number"className="text-xs"+ disabled={config.isArchived}onBlur={handleOnBlur({config,field,@@ -678,9 +713,10 @@ export function AnnotateButton({((config.categories as ConfigCategory[]) ??[]- ).length > 3 ? (+ ).length > 2 ? (<SelectdefaultValue={score.stringValue}+ disabled={config.isArchived}onValueChange={handleOnValueChange(score,index,@@ -714,6 +750,7 @@ export function AnnotateButton({<ToggleGrouptype="single"defaultValue={score.stringValue}+ disabled={config.isArchived}className={`grid grid-cols-${((config.categories as ConfigCategory[]) ?? [])?.length}`}onValueChange={handleOnValueChange(score,@@ -748,31 +785,80 @@ export function AnnotateButton({</FormItem>)}/>- <Button- variant="link"- type="button"- className="px-0 pl-1"- title="Delete score from trace/observation"- disabled={isScoreUnsaved(score.scoreId)}- loading={mutDeleteScore.isLoading}- onClick={async () => {- if (score.scoreId) {- await mutDeleteScore.mutateAsync({- id: score.scoreId,- projectId,- });- capture("score:delete", {- type: type,- source: source,- });- form.clearErrors(- `scoreData.${index}.value`,- );- }- }}- >- <X className="h-4 w-4" />- </Button>+ {config.isArchived ? (+ <Popover key={score.id}>+ <PopoverTrigger asChild>+ <Button+ variant="link"+ type="button"+ className="px-0 pl-1"+ title="Delete archived score"+ disabled={isScoreUnsaved(score.scoreId)}+ >+ <Archive className="h-4 w-4"></Archive>+ </Button>+ </PopoverTrigger>+ <PopoverContent>+ <h2 className="text-md mb-3 font-semibold">+ Your score is archived+ </h2>+ <p className="mb-3 text-sm">+ This action will delete your score+ irreversibly.+ </p>+ <div className="flex justify-end space-x-4">+ <Button+ type="button"+ variant="destructive"+ loading={mutDeleteScore.isLoading}+ onClick={async () => {+ if (score.scoreId) {+ await mutDeleteScore.mutateAsync({+ id: score.scoreId,+ projectId,+ });+ capture("score:delete", {+ type: type,+ source: source,+ });+ form.clearErrors(+ `scoreData.${index}.value`,+ );+ }+ }}+ >+ Delete+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ ) : (+ <Button+ variant="link"+ type="button"+ className="px-0 pl-1"+ title="Delete score from trace/observation"+ disabled={isScoreUnsaved(score.scoreId)}+ loading={mutDeleteScore.isLoading}+ onClick={async () => {+ if (score.scoreId) {+ await mutDeleteScore.mutateAsync({+ id: score.scoreId,+ projectId,+ });+ capture("score:delete", {+ type: type,+ source: source,+ });+ form.clearErrors(+ `scoreData.${index}.value`,+ );+ }+ }}+ >+ <X className="h-4 w-4" />+ </Button>+ )}</div></div>);diff --git a/web/src/features/manual-scoring/components/multi-select-key-values.tsx b/web/src/features/manual-scoring/components/multi-select-key-values.tsxindex b2b3e9e760..81f1230ae6 100644--- a/web/src/features/manual-scoring/components/multi-select-key-values.tsx+++ b/web/src/features/manual-scoring/components/multi-select-key-values.tsx@@ -1,5 +1,5 @@import * as React from "react";-import { Check, ChevronDown } from "lucide-react";+import { Archive, Check, ChevronDown } from "lucide-react";import { cn } from "@/src/utils/tailwind";import { Badge } from "@/src/components/ui/badge";@@ -25,6 +25,7 @@ type MultiSelectOptions = {key?: string;count?: number;disabled?: boolean;+ isArchived?: boolean;};export function MultiSelectKeyValues<@@ -157,9 +158,21 @@ export function MultiSelectKeyValues<option.disabled ? "opacity-50" : null,)}>- <Check className={cn("h-4 w-4")} />+ <Check className="h-4 w-4" /></div>- <span className="overflow-x-scroll">{option.value}</span>+ <span+ className={cn(+ "overflow-x-scroll",+ option.isArchived ? "text-foreground/50" : "",+ )}+ >+ {option.value}+ </span>+ {option.isArchived ? (+ <div className="ml-1 mt-1 flex h-4 w-4">+ <Archive className="h-4 w-4 text-foreground/50"></Archive>+ </div>+ ) : null}{option.count !== undefined ? (<span className="ml-auto flex h-4 w-4 items-center justify-center pl-1 font-mono text-xs">{option.count}diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex a30b92b7ab..11164066e9 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -37,7 +37,12 @@ const events = {"update_comment","delete_comment",],- score_configs: ["create_form_submit", "manage_configs_item_click"],+ score_configs: [+ "create_form_submit",+ "manage_configs_item_click",+ "archive_form_open",+ "archive_form_submit",+ ],models: ["delete_button_click", "new_form_submit", "new_form_open"],prompts: ["new_form_submit",diff --git a/web/src/server/api/routers/scoreConfigs.ts b/web/src/server/api/routers/scoreConfigs.tsindex 7b740d40af..94c5e913b0 100644--- a/web/src/server/api/routers/scoreConfigs.ts+++ b/web/src/server/api/routers/scoreConfigs.ts@@ -58,7 +58,6 @@ export const scoreConfigsRouter = createTRPCRouter({console.log(error);}}),-create: protectedProjectProcedure.input(z.object({@@ -98,6 +97,37 @@ export const scoreConfigsRouter = createTRPCRouter({},});+ return config;+ } catch (error) {+ console.log(error);+ }+ }),+ update: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ id: z.string(),+ isArchived: z.boolean(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "scoreConfigs:CUD",+ });++ try {+ const config = await ctx.prisma.scoreConfig.update({+ where: {+ id: input.id,+ projectId: input.projectId,+ },+ data: {+ isArchived: input.isArchived,+ },+ });+return config;} catch (error) {console.log(error);