🪢 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(evaluators): add updates (#4360)
Hassieb Pakzadc0ebd06c0ca4
diff --git a/web/src/ee/features/evals/components/evaluator-detail.tsx b/web/src/ee/features/evals/components/evaluator-detail.tsxindex c8c2c93b22..e48f346a12 100644--- a/web/src/ee/features/evals/components/evaluator-detail.tsx+++ b/web/src/ee/features/evals/components/evaluator-detail.tsx@@ -11,7 +11,6 @@ import {PopoverTrigger,} from "@/src/components/ui/popover";import { useState } from "react";-import { Trash } from "lucide-react";import TableLink from "@/src/components/table/table-link";import EvalLogTable from "@/src/ee/features/evals/components/eval-log";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -20,12 +19,23 @@ import { TableWithMetadataWrapper } from "@/src/components/table/TableWithMetadaimport { StatusBadge } from "@/src/components/layouts/status-badge";import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";import { CardDescription } from "@/src/components/ui/card";+import { EvaluatorStatus } from "@/src/ee/features/evals/types";+import { Switch } from "@/src/components/ui/switch";+import { Edit } from "lucide-react";+import {+ Dialog,+ DialogContent,+ DialogTitle,+ DialogTrigger,+} from "@/src/components/ui/dialog";export const EvaluatorDetail = () => {const router = useRouter();const projectId = router.query.projectId as string;const evaluatorId = router.query.evaluatorId as string;+ const [isEditOpen, setIsEditOpen] = useState(false);+// get the current template by idconst evaluator = api.evals.configById.useQuery({projectId: projectId,@@ -63,79 +73,102 @@ export const EvaluatorDetail = () => {return (<FullScreenPage>- <>- <Header- title={evaluator.data?.id ?? "Loading..."}- breadcrumb={[- {- name: "Evaluators",- href: `/project/${router.query.projectId as string}/evals`,- },- { name: evaluator.data?.id },- ]}- actionButtons={- <>- <DeactivateEvaluator- projectId={projectId}- evaluator={evaluator.data ?? undefined}- isLoading={evaluator.isLoading}+ <Header+ title={evaluator.data ? `Evaluator ${evaluator.data.id}` : "Loading..."}+ breadcrumb={[+ {+ name: "Evaluators",+ href: `/project/${router.query.projectId as string}/evals`,+ },+ { name: evaluator.data?.id },+ ]}+ actionButtons={+ <>+ <StatusBadge+ type={evaluator.data?.status.toLowerCase()}+ isLive+ className="max-h-8"+ />+ <DeactivateEvaluator+ projectId={projectId}+ evaluator={evaluator.data ?? undefined}+ isLoading={evaluator.isLoading}+ />+ {evaluator.data && (+ <DetailPageNav+ key="nav"+ currentId={encodeURIComponent(evaluator.data.id)}+ path={(entry) =>+ `/project/${projectId}/evals/${encodeURIComponent(entry.id)}`+ }+ listKey="evals"/>- {evaluator.data && (- <DetailPageNav- key="nav"- currentId={encodeURIComponent(evaluator.data.id)}- path={(entry) =>- `/project/${projectId}/evals/${encodeURIComponent(entry.id)}`- }- listKey="evals"+ )}+ </>+ }+ />+ {existingEvaluator && (+ <TableWithMetadataWrapper+ tableComponent={+ <EvalLogTable+ projectId={projectId}+ jobConfigurationId={existingEvaluator.id}+ />+ }+ cardTitleChildren={+ <div className="flex w-full flex-row items-center justify-between">+ <span>Evaluator configuration</span>+ <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>+ <DialogTrigger asChild>+ <Button variant="outline" className="flex items-center gap-2">+ <Edit className="h-4 w-4" />+ </Button>+ </DialogTrigger>+ <DialogContent className="max-w-screen-xl">+ <DialogTitle>Edit Evaluator</DialogTitle>+ <div className="max-h-[80vh] overflow-y-auto">+ <EvaluatorForm+ key={existingEvaluator.id}+ projectId={projectId}+ evalTemplates={allTemplates.data?.templates}+ existingEvaluator={existingEvaluator}+ shouldWrapVariables={true}+ mode="edit"+ onFormSuccess={() => {+ setIsEditOpen(false);+ // Force a reload as the form state is not properly updated+ void router.reload();+ }}+ />+ </div>+ </DialogContent>+ </Dialog>+ </div>+ }+ cardContentChildren={+ <>+ <CardDescription className="flex items-center justify-between text-sm">+ <span className="text-sm font-medium">Eval Template</span>+ <TableLink+ path={`/project/${projectId}/evals/templates/${existingEvaluator.evalTemplateId}`}+ value={`${existingEvaluator.evalTemplate.name} (v${existingEvaluator.evalTemplate.version})`}+ className="flex min-h-6 items-center"/>- )}+ </CardDescription>+ <div className="flex w-full flex-col items-start justify-between space-y-2 pb-4">+ <EvaluatorForm+ key={existingEvaluator.id}+ projectId={projectId}+ evalTemplates={allTemplates.data?.templates}+ existingEvaluator={existingEvaluator}+ disabled={true}+ shouldWrapVariables={true}+ />+ </div></>}/>- {existingEvaluator && (- <TableWithMetadataWrapper- tableComponent={- <EvalLogTable- projectId={projectId}- jobConfigurationId={existingEvaluator.id}- />- }- cardTitleChildren={- <div className="flex w-full flex-row items-center justify-between">- <span>Evaluator</span>- <StatusBadge- type={evaluator.data?.status.toLowerCase()}- isLive- className="max-h-8"- />- </div>- }- cardContentChildren={- <>- <CardDescription className="flex items-center justify-between text-sm">- <span className="text-sm font-medium">Eval Template</span>- <TableLink- path={`/project/${projectId}/evals/templates/${existingEvaluator.evalTemplateId}`}- value={`${existingEvaluator.evalTemplate.name} (v${existingEvaluator.evalTemplate.version})`}- className="flex min-h-6 items-center"- />- </CardDescription>- <div className="flex w-full flex-col items-start justify-between space-y-2 pb-4">- <EvaluatorForm- key={existingEvaluator.id}- projectId={projectId}- evalTemplates={allTemplates.data?.templates}- existingEvaluator={existingEvaluator}- disabled={true}- shouldWrapVariables={true}- />- </div>- </>- }- />- )}- </>+ )}</FullScreenPage>);};@@ -143,7 +176,6 @@ export const EvaluatorDetail = () => {export function DeactivateEvaluator({projectId,evaluator,- isLoading,}: {projectId: string;evaluator?: RouterOutputs["evals"]["configById"];@@ -153,6 +185,7 @@ export function DeactivateEvaluator({const hasAccess = useHasProjectAccess({ projectId, scope: "evalJob:CUD" });const [isOpen, setIsOpen] = useState(false);const capture = usePostHogClientCapture();+ const isActive = evaluator?.status === EvaluatorStatus.ACTIVE;const mutEvaluator = api.evals.updateEvalJob.useMutation({onSuccess: () => {@@ -165,41 +198,50 @@ export function DeactivateEvaluator({console.error("Project ID is missing");return;}++ const prevStatus = evaluator?.status;+mutEvaluator.mutateAsync({projectId,evalConfigId: evaluator?.id ?? "",- updatedStatus: "INACTIVE",+ config: {+ status: isActive ? EvaluatorStatus.INACTIVE : EvaluatorStatus.ACTIVE,+ },});- capture("eval_config:delete");+ capture(+ prevStatus === EvaluatorStatus.ACTIVE+ ? "eval_config:deactivate"+ : "eval_config:activate",+ );setIsOpen(false);};return (<Popover open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}><PopoverTrigger asChild>- <Button- variant="outline"- size={"icon"}- disabled={!hasAccess || evaluator?.status !== "ACTIVE"}- loading={isLoading}- >- <Trash className="h-5 w-5" />- </Button>+ <div className="flex items-center">+ <Switch+ disabled={!hasAccess}+ checked={isActive}+ className={isActive ? "data-[state=checked]:bg-dark-green" : ""}+ />+ </div></PopoverTrigger><PopoverContent><h2 className="text-md mb-3 font-semibold">Please confirm</h2><p className="mb-3 text-sm">- This action permanently deactivates the evaluator. No more traces will- be evaluated based on this evaluator.+ {evaluator?.status === "ACTIVE"+ ? "This action will deactivate the evaluator. No more traces will be evaluated based on this evaluator."+ : "This action will activate the evaluator. New traces will be evaluated based on this evaluator."}</p><div className="flex justify-end space-x-4"><Buttontype="button"- variant="destructive"+ variant={evaluator?.status === "ACTIVE" ? "destructive" : "default"}loading={mutEvaluator.isLoading}onClick={onClick}>- Deactivate evaluator+ {evaluator?.status === "ACTIVE" ? "Deactivate" : "Activate"}</Button></div></PopoverContent>diff --git a/web/src/ee/features/evals/components/evaluator-form.tsx b/web/src/ee/features/evals/components/evaluator-form.tsxindex 66500a5445..bd7f5dd24f 100644--- a/web/src/ee/features/evals/components/evaluator-form.tsx+++ b/web/src/ee/features/evals/components/evaluator-form.tsx@@ -87,6 +87,7 @@ export const EvaluatorForm = (props: {disabled?: boolean;existingEvaluator?: JobConfiguration & { evalTemplate: EvalTemplate };onFormSuccess?: () => void;+ mode?: "create" | "edit";shouldWrapVariables?: boolean;}) => {const [open, setOpen] = useState(false);@@ -131,7 +132,7 @@ export const EvaluatorForm = (props: {<Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild><Button- disabled={props.disabled}+ disabled={props.disabled || props.mode === "edit"}variant="outline"role="combobox"aria-expanded={open}@@ -193,7 +194,11 @@ export const EvaluatorForm = (props: {<Popover><PopoverTrigger asChild><Button- disabled={props.disabled || !selectedTemplateName}+ disabled={+ props.disabled ||+ !selectedTemplateName ||+ props.mode === "edit"+ }variant="outline"role="combobox"className="w-1/3 justify-between px-2 font-normal"@@ -276,6 +281,7 @@ export const EvaluatorForm = (props: {}onFormSuccess={props.onFormSuccess}shouldWrapVariables={props.shouldWrapVariables}+ mode={props.mode}/>) : null}</>@@ -289,6 +295,7 @@ export const InnerEvalConfigForm = (props: {existingEvaluator?: JobConfiguration;onFormSuccess?: () => void;shouldWrapVariables?: boolean;+ mode?: "create" | "edit";}) => {const [formError, setFormError] = useState<string | null>(null);const capture = usePostHogClientCapture();@@ -393,6 +400,10 @@ export const InnerEvalConfigForm = (props: {onSuccess: () => utils.models.invalidate(),onError: (error) => setFormError(error.message),});+ const updateJobMutation = api.evals.updateEvalJob.useMutation({+ onSuccess: () => utils.evals.invalidate(),+ onError: (error) => setFormError(error.message),+ });const [availableVariables, setAvailableVariables] = useState<typeof availableTraceEvalVariables | typeof availableDatasetEvalVariables>(@@ -402,7 +413,11 @@ export const InnerEvalConfigForm = (props: {);function onSubmit(values: z.infer<typeof formSchema>) {- capture("eval_config:new_form_submit");+ capture(+ props.mode === "edit"+ ? "eval_config:update"+ : "eval_config:new_form_submit",+ );const validatedFilter = z.array(singleFilter).safeParse(values.filter);@@ -427,21 +442,42 @@ export const InnerEvalConfigForm = (props: {return;}- createJobMutation- .mutateAsync({- projectId: props.projectId,- evalTemplateId: props.evalTemplate.id,- scoreName: values.scoreName,- target: values.target,- filter: validatedFilter.data,- mapping: validatedVarMapping.data,- sampling: values.sampling,- delay: values.delay * 1000, // multiply by 1k to convert to ms- })+ const delay = values.delay * 1000; // convert to ms+ const sampling = values.sampling;+ const mapping = validatedVarMapping.data;+ const filter = validatedFilter.data;+ const scoreName = values.scoreName;++ (props.mode === "edit" && props.existingEvaluator+ ? updateJobMutation.mutateAsync({+ projectId: props.projectId,+ evalConfigId: props.existingEvaluator.id,+ config: {+ delay,+ filter,+ variableMapping: mapping,+ sampling,+ scoreName,+ },+ })+ : createJobMutation.mutateAsync({+ projectId: props.projectId,+ target: values.target,+ evalTemplateId: props.evalTemplate.id,+ scoreName,+ filter,+ mapping,+ sampling,+ delay,+ })+ ).then(() => {- props.onFormSuccess?.();form.reset();- void router.push(`/project/${props.projectId}/evals`);+ props.onFormSuccess?.();++ if (props.mode !== "edit") {+ void router.push(`/project/${props.projectId}/evals`);+ }}).catch((error) => {// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access@@ -507,10 +543,16 @@ export const InnerEvalConfigForm = (props: {}}><TabsList>- <TabsTrigger value="trace" disabled={props.disabled}>+ <TabsTrigger+ value="trace"+ disabled={props.disabled || props.mode === "edit"}+ >Trace</TabsTrigger>- <TabsTrigger value="dataset" disabled={props.disabled}>+ <TabsTrigger+ value="dataset"+ disabled={props.disabled || props.mode === "edit"}+ >Dataset</TabsTrigger></TabsList>@@ -825,7 +867,7 @@ export const InnerEvalConfigForm = (props: {{!props.disabled ? (<Buttontype="submit"- loading={createJobMutation.isLoading}+ loading={createJobMutation.isLoading || updateJobMutation.isLoading}className="mt-3">Savediff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.tsindex d63bb710f6..8c0a336dbe 100644--- a/web/src/ee/features/evals/server/router.ts+++ b/web/src/ee/features/evals/server/router.ts@@ -26,6 +26,7 @@ import {} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";import { EvalReferencedEvaluators } from "@/src/ee/features/evals/types";+import { EvaluatorStatus } from "../types";import { traceException } from "@langfuse/shared/src/server";const APIEvaluatorSchema = z.object({@@ -85,6 +86,26 @@ export const CreateEvalTemplate = z.object({.default(EvalReferencedEvaluators.PERSIST),});+const CreateEvalJobSchema = z.object({+ projectId: z.string(),+ evalTemplateId: z.string(),+ scoreName: z.string().min(1),+ target: z.string(),+ filter: z.array(singleFilter).nullable(), // re-using the filter type from the tables+ mapping: z.array(variableMapping),+ sampling: z.number().gt(0).lte(1),+ delay: z.number().gte(0).default(DEFAULT_TRACE_JOB_DELAY), // 10 seconds default+});++const UpdateEvalJobSchema = z.object({+ scoreName: z.string().min(1).optional(),+ filter: z.array(singleFilter).optional(),+ variableMapping: z.array(variableMapping).optional(),+ sampling: z.number().gt(0).lte(1).optional(),+ delay: z.number().gte(0).optional(),+ status: z.nativeEnum(EvaluatorStatus).optional(),+});+export const evalRouter = createTRPCRouter({allConfigs: protectedProjectProcedure.input(@@ -428,18 +449,7 @@ export const evalRouter = createTRPCRouter({}),createJob: protectedProjectProcedure- .input(- z.object({- projectId: z.string(),- evalTemplateId: z.string(),- scoreName: z.string().min(1),- target: z.string(),- filter: z.array(singleFilter).nullable(), // re-using the filter type from the tables- mapping: z.array(variableMapping),- sampling: z.number().gte(0).lte(1),- delay: z.number().gte(0).default(DEFAULT_TRACE_JOB_DELAY), // 10 seconds default- }),- )+ .input(CreateEvalJobSchema).mutation(async ({ input, ctx }) => {try {throwIfNoEntitlement({@@ -613,7 +623,7 @@ export const evalRouter = createTRPCRouter({z.object({projectId: z.string(),evalConfigId: z.string(),- updatedStatus: z.enum(["ACTIVE", "INACTIVE"]),+ config: UpdateEvalJobSchema,}),).mutation(async ({ input, ctx }) => {@@ -633,9 +643,7 @@ export const evalRouter = createTRPCRouter({id: input.evalConfigId,projectId: input.projectId,},- data: {- status: input.updatedStatus,- },+ data: input.config,});await auditLog({diff --git a/web/src/ee/features/evals/types.ts b/web/src/ee/features/evals/types.tsindex 1a0f30f439..b325aa5d06 100644--- a/web/src/ee/features/evals/types.ts+++ b/web/src/ee/features/evals/types.ts@@ -1,4 +1,11 @@+import { z } from "zod";+import { JobConfigState } from "@langfuse/shared";+export enum EvalReferencedEvaluators {UPDATE = "update",PERSIST = "persist",}++export const EvaluatorStatus = JobConfigState;+export const EvaluatorStatusSchema = z.nativeEnum(EvaluatorStatus);+export type EvaluatorStatusType = z.infer<typeof EvaluatorStatusSchema>;diff --git a/web/src/ee/features/experiments/components/CreateExperimentsForm.tsx b/web/src/ee/features/experiments/components/CreateExperimentsForm.tsxindex 9fff10ff89..3cff8521ff 100644--- a/web/src/ee/features/experiments/components/CreateExperimentsForm.tsx+++ b/web/src/ee/features/experiments/components/CreateExperimentsForm.tsx@@ -65,6 +65,7 @@ import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccesimport { PromptType } from "@/src/features/prompts/server/utils/validation";import { Skeleton } from "@/src/components/ui/skeleton";import { Input } from "@/src/components/ui/input";+import { EvaluatorStatus } from "@/src/ee/features/evals/types";const CreateExperimentData = z.object({name: z.string().min(1, "Please enter a name").optional(),@@ -326,7 +327,12 @@ export const CreateExperimentsForm = ({archiveEvaluatorMutation.mutate({projectId,evalConfigId: changedValueId,- updatedStatus: evaluator.status === "INACTIVE" ? "ACTIVE" : "INACTIVE",+ config: {+ status:+ evaluator.status === EvaluatorStatus.INACTIVE+ ? EvaluatorStatus.ACTIVE+ : EvaluatorStatus.INACTIVE,+ },});setSelectedEvaluators(values);diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex d154f3863a..4213ffe1ca 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -59,7 +59,13 @@ const events = {"version_delete_submit",],session_detail: ["publish_button_click"],- eval_config: ["delete", "new_form_submit", "new_form_open"],+ eval_config: [+ "new_form_submit",+ "new_form_open",+ "activate",+ "deactivate",+ "update",+ ],eval_templates: ["view_version","new_form_open",