Skip to content

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

feat: ui for eval config creation (#1673)

Max Deichmann4dcdb01429fe
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 129c540d65..71188c0df4 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -50,6 +50,11 @@ export const JobType = {
EVAL: "EVAL"
} as const;
export type JobType = (typeof JobType)[keyof typeof JobType];
+export const JobConfigState = {
+ ACTIVE: "ACTIVE",
+ INACTIVE: "INACTIVE"
+} as const;
+export type JobConfigState = (typeof JobConfigState)[keyof typeof JobConfigState];
export const JobExecutionStatus = {
COMPLETED: "COMPLETED",
ERROR: "ERROR",
@@ -170,6 +175,7 @@ export type JobConfiguration = {
updated_at: Generated<Timestamp>;
project_id: string;
job_type: JobType;
+ status: Generated<JobConfigState>;
eval_template_id: string | null;
score_name: string;
filter: unknown;
diff --git a/packages/shared/prisma/migrations/20240411194142_update_job_config_status/migration.sql b/packages/shared/prisma/migrations/20240411194142_update_job_config_status/migration.sql
new file mode 100644
index 0000000000..b476181cfc
--- /dev/null
+++ b/packages/shared/prisma/migrations/20240411194142_update_job_config_status/migration.sql
@@ -0,0 +1,5 @@
+-- CreateEnum
+CREATE TYPE "JobConfigState" AS ENUM ('ACTIVE', 'INACTIVE');
+
+-- AlterTable
+ALTER TABLE "job_configurations" ADD COLUMN "status" "JobConfigState" NOT NULL DEFAULT 'ACTIVE';
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 44579f46b1..cf3b725be0 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -616,6 +616,11 @@ enum JobType {
EVAL
}
+enum JobConfigState {
+ ACTIVE
+ INACTIVE
+}
+
model JobConfiguration {
id String @id @default(cuid())
createdAt DateTime @default(now()) @map("created_at")
@@ -624,9 +629,10 @@ model JobConfiguration {
projectId String @map("project_id")
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- jobType JobType @map("job_type")
- evalTemplateId String? @map("eval_template_id")
- evalTemplate EvalTemplate? @relation(fields: [evalTemplateId], references: [id], onDelete: SetNull)
+ jobType JobType @map("job_type")
+ status JobConfigState @default(ACTIVE)
+ evalTemplateId String? @map("eval_template_id")
+ evalTemplate EvalTemplate? @relation(fields: [evalTemplateId], references: [id], onDelete: SetNull)
scoreName String @map("score_name")
filter Json
diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.ts
index d0cfff9357..e9609a9fb7 100644
--- a/packages/shared/prisma/seed.ts
+++ b/packages/shared/prisma/seed.ts
@@ -165,6 +165,74 @@ async function main() {
await uploadObjects(traces, observations, scores, sessions, events);
+ // add eval objects
+ const evalTemplate = await prisma.evalTemplate.upsert({
+ where: {
+ projectId_name_version: {
+ projectId: project1.id,
+ name: "toxicity-template",
+ version: 1,
+ },
+ },
+ create: {
+ projectId: project1.id,
+ name: "toxicity-template",
+ version: 1,
+ prompt:
+ "Please evaluate the toxicity of the following text {{input}} {{output}}",
+ model: "gpt-3.5-turbo",
+ vars: ["input", "output"],
+ outputSchema: {
+ score: "provide a score between 0 and 1",
+ reasoning: "one sentence reasoning for the score",
+ },
+ modelParams: {
+ temperature: 0.7,
+ outputTokenLimit: 100,
+ topP: 0.9,
+ },
+ },
+ update: {},
+ });
+
+ await prisma.jobConfiguration.upsert({
+ where: {
+ id: "toxicity-job",
+ },
+ create: {
+ id: "toxicity-job",
+ evalTemplateId: evalTemplate.id,
+ projectId: project1.id,
+ jobType: "EVAL",
+ status: "ACTIVE",
+ scoreName: "toxicity",
+ filter: [
+ {
+ type: "string",
+ value: "user",
+ column: "User ID",
+ operator: "contains",
+ },
+ ],
+ variableMapping: [
+ {
+ langfuseObject: "trace",
+ selectedColumnId: "input",
+ templateVariable: "input",
+ },
+ {
+ langfuseObject: "trace",
+ selectedColumnId: "metadata",
+ templateVariable: "output",
+ },
+ ],
+ targetObject: "trace",
+ sampling: 1,
+ delay: 5_000,
+ },
+ update: {},
+ });
+
for (let datasetNumber = 0; datasetNumber < 2; datasetNumber++) {
const dataset = await prisma.dataset.create({
data: {
diff --git a/packages/shared/src/interfaces/filters.ts b/packages/shared/src/interfaces/filters.ts
index 39a02eac9b..056bad0dcb 100644
--- a/packages/shared/src/interfaces/filters.ts
+++ b/packages/shared/src/interfaces/filters.ts
@@ -20,7 +20,7 @@ export const filterOperators = {
export const timeFilter = z.object({
column: z.string(),
operator: z.enum(filterOperators.datetime),
- value: z.date(),
+ value: z.coerce.date(), // coerce required to parse stringified dates from the db in evals
type: z.literal("datetime"),
});
export const stringFilter = z.object({
diff --git a/packages/shared/src/server/evals/types.ts b/packages/shared/src/server/evals/types.ts
index bc92b8c9ca..b9be1267e3 100644
--- a/packages/shared/src/server/evals/types.ts
+++ b/packages/shared/src/server/evals/types.ts
@@ -6,11 +6,12 @@ export const evalObjects = [
id: "trace",
display: "Trace",
availableColumns: [
- ...tracesTableCols.map((c) => ({
- name: c.name,
- id: c.id,
- internal: c.internal,
- })),
+ {
+ name: "Metadata",
+ id: "metadata",
+ type: "stringObject",
+ internal: 'o."metadata"',
+ },
{ name: "Input", id: "input", internal: 't."input"' },
{ name: "Output", id: "output", internal: 't."output"' },
],
@@ -19,11 +20,12 @@ export const evalObjects = [
id: "span",
display: "Span",
availableColumns: [
- ...observationsTableCols.map((c) => ({
- name: c.name,
- id: c.id,
- internal: c.internal,
- })),
+ {
+ name: "Metadata",
+ id: "metadata",
+ type: "stringObject",
+ internal: 'o."metadata"',
+ },
{ name: "Input", id: "input", internal: 'o."input"' },
{ name: "Output", id: "output", internal: 'o."output"' },
],
@@ -32,11 +34,12 @@ export const evalObjects = [
id: "generation",
display: "Generation",
availableColumns: [
- ...observationsTableCols.map((c) => ({
- name: c.name,
- id: c.id,
- internal: c.internal,
- })),
+ {
+ name: "Metadata",
+ id: "metadata",
+ type: "stringObject",
+ internal: 'o."metadata"',
+ },
{ name: "Input", id: "input", internal: 'o."input"' },
{ name: "Output", id: "output", internal: 'o."output"' },
],
diff --git a/web/src/components/date-picker.tsx b/web/src/components/date-picker.tsx
index 7314b9bb98..b253417abc 100644
--- a/web/src/components/date-picker.tsx
+++ b/web/src/components/date-picker.tsx
@@ -40,11 +40,13 @@ export function DatePicker({
onChange,
clearable = false,
className,
+ disabled,
}: {
date?: Date | undefined;
onChange: (date: Date | undefined) => void;
clearable?: boolean;
className?: string;
+ disabled?: boolean;
}) {
return (
<div className="flex flex-row gap-2 align-middle">
@@ -52,6 +54,7 @@ export function DatePicker({
<PopoverTrigger asChild>
<Button
variant={"outline"}
+ disabled={disabled}
className={cn(
"justify-start text-left font-normal",
!date && "text-muted-foreground",
diff --git a/web/src/components/layouts/status-badge.tsx b/web/src/components/layouts/status-badge.tsx
index 3bd2ca99ad..96cabe02e3 100644
--- a/web/src/components/layouts/status-badge.tsx
+++ b/web/src/components/layouts/status-badge.tsx
@@ -1,7 +1,7 @@
import { cn } from "@/src/utils/tailwind";
const statusCategories = {
- active: ["production", "live"],
+ active: ["production", "live", "active"],
inactive: ["disabled", "inactive"],
};
diff --git a/web/src/features/evals/components/eval-config-detail.tsx b/web/src/features/evals/components/eval-config-detail.tsx
new file mode 100644
index 0000000000..15d6d4b03f
--- /dev/null
+++ b/web/src/features/evals/components/eval-config-detail.tsx
@@ -0,0 +1,144 @@
+import * as React from "react";
+import Header from "@/src/components/layouts/header";
+import { RouterOutputs, api } from "@/src/utils/api";
+import { useRouter } from "next/router";
+import { EvalConfigForm } from "@/src/features/evals/components/eval-config-form";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { Button } from "@/src/components/ui/button";
+import { Pencil } from "lucide-react";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { useState } from "react";
+
+export const EvalConfigDetail = () => {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const configId = router.query.configId as string;
+
+ // get the current template by id
+ const config = api.evals.configById.useQuery({
+ projectId: projectId,
+ id: configId,
+ });
+
+ // get all templates for the current template name
+ const allTemplates = api.evals.allTemplatesForName.useQuery(
+ {
+ projectId: projectId,
+ name: config.data?.evalTemplate?.name ?? "",
+ },
+ {
+ enabled: !config.isLoading && !config.isError,
+ },
+ );
+
+ if (
+ config.isLoading ||
+ !config.data ||
+ allTemplates.isLoading ||
+ !allTemplates.data
+ ) {
+ return <div>Loading...</div>;
+ }
+
+ if (config.data && config.data.evalTemplate === null) {
+ return <div>Config not found</div>;
+ }
+
+ return (
+ <div className="md:container">
+ <Header
+ title={config.data?.id ?? "Loading..."}
+ status={config.data?.status.toLowerCase()}
+ actionButtons={
+ <DeactivateConfig
+ projectId={projectId}
+ config={config.data ?? undefined}
+ isLoading={config.isLoading}
+ />
+ }
+ />
+ <EvalConfigForm
+ projectId={projectId}
+ evalTemplates={allTemplates.data?.templates}
+ existingEvalConfig={
+ config.data && config.data.evalTemplate
+ ? { ...config.data, evalTemplate: config.data.evalTemplate }
+ : undefined
+ }
+ disabled={true}
+ />
+ </div>
+ );
+};
+
+export function DeactivateConfig({
+ projectId,
+ config,
+ isLoading,
+}: {
+ projectId: string;
+ config?: RouterOutputs["evals"]["configById"];
+ isLoading: boolean;
+}) {
+ const utils = api.useUtils();
+ const hasAccess = useHasAccess({ projectId, scope: "job:CUD" });
+ const [isOpen, setIsOpen] = useState(false);
+
+ const mutEvalConfig = api.evals.updateEvalJob.useMutation({
+ onSuccess: () => {
+ void utils.evals.invalidate();
+ },
+ });
+
+ const onClick = () => {
+ mutEvalConfig.mutateAsync({
+ projectId,
+ evalConfigId: config?.id ?? "",
+ updatedStatus: "INACTIVE",
+ });
+ };
+
+ return (
+ <Popover open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="ghost"
+ size={"sm"}
+ onClick={() => void onClick()}
+ disabled={!hasAccess || config?.status !== "ACTIVE"}
+ loading={isLoading}
+ >
+ <Pencil className="h-5 w-5" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent>
+ <h2 className="text-md mb-3 font-semibold">Please confirm</h2>
+ <p className="mb-3 text-sm">
+ This action permanently deactivates the evaluation job. No more traces
+ will be evaluated for this job.
+ </p>
+ <div className="flex justify-end space-x-4">
+ <Button
+ type="button"
+ variant="destructive"
+ loading={mutEvalConfig.isLoading}
+ onClick={() => {
+ if (!projectId) {
+ console.error("Project ID is missing");
+ return;
+ }
+ void onClick();
+ setIsOpen(false);
+ }}
+ >
+ Deactivate Eval Job
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/web/src/features/evals/components/eval-config-form.tsx b/web/src/features/evals/components/eval-config-form.tsx
new file mode 100644
index 0000000000..a69db217fd
--- /dev/null
+++ b/web/src/features/evals/components/eval-config-form.tsx
@@ -0,0 +1,489 @@
+import { usePostHog } from "posthog-js/react";
+import { useFieldArray, useForm } from "react-hook-form";
+import { Input } from "@/src/components/ui/input";
+import { Button } from "@/src/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
+import {
+ tracesTableColsWithOptions,
+ singleFilter,
+ JobConfiguration,
+} from "@langfuse/shared";
+import * as z from "zod";
+import { useEffect, useState } from "react";
+import { api } from "@/src/utils/api";
+import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";
+import {
+ type EvalTemplate,
+ variableMapping,
+ wipVariableMapping,
+ evalObjects,
+} from "@langfuse/shared";
+import router from "next/router";
+import { Slider } from "@/src/components/ui/slider";
+import { Card } from "@/src/components/ui/card";
+
+const formSchema = z.object({
+ evalTemplateId: z.string(),
+ scoreName: z.string(),
+ target: z.string(),
+ filter: z.array(singleFilter).nullable(), // re-using the filter type from the tables
+ mapping: z.array(wipVariableMapping),
+ sampling: z.coerce.number().gte(0).lte(1),
+ delay: z.coerce.number().optional().default(10),
+});
+
+export const EvalConfigForm = (props: {
+ projectId: string;
+ evalTemplates: EvalTemplate[];
+ disabled?: boolean;
+ existingEvalConfig?: JobConfiguration & { evalTemplate: EvalTemplate };
+ onFormSuccess?: () => void;
+}) => {
+ const [formError, setFormError] = useState<string | null>(null);
+ const posthog = usePostHog();
+ const form = useForm<z.infer<typeof formSchema>>({
+ resolver: zodResolver(formSchema),
+ disabled: props.disabled,
+ defaultValues: {
+ evalTemplateId: props.existingEvalConfig?.evalTemplate.id ?? "",
+ scoreName: props.existingEvalConfig?.scoreName ?? "",
+ target: props.existingEvalConfig?.targetObject ?? "",
+ filter: props.existingEvalConfig?.filter
+ ? z.array(singleFilter).parse(props.existingEvalConfig.filter)
+ : [],
+ mapping: props.existingEvalConfig?.variableMapping
+ ? z
+ .array(variableMapping)
+ .parse(props.existingEvalConfig.variableMapping)
+ : z.array(variableMapping).parse([]),
+ sampling: props.existingEvalConfig?.sampling
+ ? props.existingEvalConfig.sampling.toNumber()
+ : 1,
+ delay: props.existingEvalConfig?.delay
+ ? props.existingEvalConfig.delay
+ : 10,
+ },
+ });
+
+ const traceFilterOptions = api.traces.filterOptions.useQuery({
+ projectId: props.projectId,
+ ...form.getFieldState("filter"),
+ });
+
+ const getSelectedEvalTemplate = props.evalTemplates.find(
+ (template) => template.id === form.watch("evalTemplateId"),
+ );
+
+ useEffect(() => {
+ if (getSelectedEvalTemplate) {
+ form.setValue("mapping", []);
+ form.setValue(
+ "mapping",
+ getSelectedEvalTemplate.vars.map((v) => ({
+ templateVariable: v,
+ langfuseObject: "trace" as const,
+ })),
+ );
+ form.setValue(
+ "scoreName",
+ `${getSelectedEvalTemplate?.name}-${getSelectedEvalTemplate?.version}`,
+ );
+ }
+ }, [form, getSelectedEvalTemplate]);
+
+ const { fields } = useFieldArray({
+ control: form.control,
+ name: "mapping",
+ });
+
+ const utils = api.useUtils();
+ const createJobMutation = api.evals.createJob.useMutation({
+ onSuccess: () => utils.models.invalidate(),
+ onError: (error) => setFormError(error.message),
+ });
+
+ function onSubmit(values: z.infer<typeof formSchema>) {
+ posthog.capture("models:new_template_form");
+
+ if (!getSelectedEvalTemplate) {
+ form.setError("evalTemplateId", {
+ type: "manual",
+ message: "Please select an eval template",
+ });
+ return;
+ }
+
+ const validatedFilter = z.array(singleFilter).safeParse(values.filter);
+
+ if (validatedFilter.success === false) {
+ form.setError("filter", {
+ type: "manual",
+ message: "Please fill out all filter fields",
+ });
+ return;
+ }
+
+ const validatedVarMapping = z
+ .array(variableMapping)
+ .safeParse(values.mapping);
+
+ if (validatedVarMapping.success === false) {
+ form.setError("mapping", {
+ type: "manual",
+ message: "Please fill out all variable mappings",
+ });
+ return;
+ }
+
+ createJobMutation
+ .mutateAsync({
+ projectId: props.projectId,
+ evalTemplateId: getSelectedEvalTemplate.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
+ })
+ .then(() => {
+ props.onFormSuccess?.();
+ form.reset();
+ void router.push(`/project/${props.projectId}/evals/configs/`);
+ })
+ .catch((error) => {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ if ("message" in error && typeof error.message === "string") {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ setFormError(error.message as string);
+ return;
+ } else {
+ setFormError(JSON.stringify(error));
+ console.error(error);
+ }
+ });
+ }
+
+ return (
+ <Form {...form}>
+ <form
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="flex flex-col gap-4"
+ >
+ <div className="grid gap-4">
+ <FormField
+ control={form.control}
+ name="evalTemplateId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Eval Template</FormLabel>
+ <Select
+ defaultValue={field.value}
+ onValueChange={(value) => {
+ field.onChange(value);
+ }}
+ >
+ <FormControl>
+ <SelectTrigger
+ disabled={props.disabled}
+ defaultValue={
+ props.existingEvalConfig?.evalTemplate
+ ? props.existingEvalConfig?.evalTemplate.id
+ : undefined
+ }
+ >
+ <SelectValue placeholder="Select a model to run this eval template" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {props.evalTemplates.map((template) => (
+ <SelectItem value={template.id} key={template.id}>
+ {`${template.name}-${template.version}`}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="scoreName"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Score Name</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Card className="flex flex-col gap-6 p-4">
+ <FormField
+ control={form.control}
+ name="target"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Target object</FormLabel>
+ <FormControl>
+ <Tabs defaultValue="trace">
+ <TabsList {...field}>
+ <TabsTrigger value="trace">Trace</TabsTrigger>
+ <TabsTrigger value="observation" disabled={true}>
+ Observation (coming soon)
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="filter"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Target filter</FormLabel>
+ <FormControl>
+ <InlineFilterBuilder
+ columns={tracesTableColsWithOptions(
+ traceFilterOptions.data,
+ )}
+ filterState={field.value ?? []}
+ onChange={(value) => field.onChange(value)}
+ disabled={props.disabled}
+ />
+ </FormControl>
+ <FormDescription>
+ This will run on all future traces that match these filters
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </Card>
+ <Card className=" p-4">
+ <FormField
+ control={form.control}
+ name="mapping"
+ render={() => (
+ <>
+ <FormLabel>Variable mapping</FormLabel>
+ <FormControl>
+ Here will some variable mapping be added.
+ </FormControl>
+ <div className="mt-2 flex flex-col gap-2">
+ {fields.map((mappingField, index) => (
+ <div className="flex gap-2" key={index}>
+ <span className="whitespace-nowrap rounded-md bg-slate-200 px-2 py-1 text-xs ">
+ {mappingField.templateVariable}
+ </span>
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-langfuseObject`}
+ name={`mapping.${index}.langfuseObject`}
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Select
+ disabled={props.disabled}
+ defaultValue={field.value}
+ onValueChange={(value) => {
+ field.onChange(value);
+ }}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Object type" />
+ </SelectTrigger>
+ <SelectContent>
+ {evalObjects.map((evalObject) => (
+ <SelectItem
+ value={evalObject.id}
+ key={evalObject.id}
+ >
+ {evalObject.display}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {form.watch(`mapping.${index}.langfuseObject`) !==
+ "trace" ? (
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-objectName`}
+ name={`mapping.${index}.objectName`}
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Input
+ {...field}
+ value={field.value ?? ""}
+ disabled={props.disabled}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ ) : undefined}
+
+ <FormField
+ control={form.control}
+ key={`${mappingField.id}-selectedColumnId`}
+ name={`mapping.${index}.selectedColumnId`}
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Select
+ disabled={props.disabled}
+ defaultValue={field.value ?? undefined}
+ onValueChange={(value) => {
+ const availableColumns = evalObjects.find(
+ (evalObject) =>
+ evalObject.id ===
+ form.watch(
+ `mapping.${index}.langfuseObject`,
+ ),
+ )?.availableColumns;
+ const column = availableColumns?.find(
+ (column) => column.id === value,
+ );
+
+ field.onChange(column?.id);
+ }}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Object type" />
+ </SelectTrigger>
+ <SelectContent>
+ {evalObjects
+ .find(
+ (evalObject) =>
+ evalObject.id ===
+ form.watch(
+ `mapping.${index}.langfuseObject`,
+ ),
+ )
+ ?.availableColumns.map((column) => (
+ <SelectItem
+ value={column.id}
+ key={column.id}
+ >
+ {column.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ ))}
+ </div>
+ <FormDescription>
+ Insert trace data into the prompt template.
+ </FormDescription>
+ <FormMessage />
+ </>
+ )}
+ />
+ </Card>
+ <Card className="flex flex-col gap-6 p-4">
+ <FormField
+ control={form.control}
+ name="sampling"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Sampling</FormLabel>
+ <FormControl>
+ <Slider
+ disabled={props.disabled}
+ min={0}
+ max={1}
+ step={0.01}
+ value={[field.value]}
+ onValueChange={(value) => field.onChange(value[0])}
+ />
+ </FormControl>
+ <div className="flex flex-col">
+ <FormDescription className="flex justify-between">
+ <span>0%</span>
+ <span>100%</span>
+ </FormDescription>
+ <FormDescription>
+ Percentage of traces to evaluate.
+ </FormDescription>
+ </div>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="delay"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Delay (seconds)</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormDescription>
+ Time between first Trace event and evaluation execution to
+ ensure all Trace data is available
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </Card>
+ </div>
+
+ {!props.disabled ? (
+ <Button
+ type="submit"
+ loading={createJobMutation.isLoading}
+ className="mt-3"
+ >
+ Save
+ </Button>
+ ) : null}
+ </form>
+ {formError ? (
+ <p className="text-red text-center">
+ <span className="font-bold">Error:</span> {formError}
+ </p>
+ ) : null}
+ </Form>
+ );
+};
diff --git a/web/src/features/evals/components/eval-config-table.tsx b/web/src/features/evals/components/eval-config-table.tsx
index 709812f989..b34afd5f34 100644
--- a/web/src/features/evals/components/eval-config-table.tsx
+++ b/web/src/features/evals/components/eval-config-table.tsx
@@ -1,18 +1,21 @@
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 useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
-import { api } from "@/src/utils/api";
-import { type JobConfiguration } from "@prisma/client";
+import { InlineFilterState } from "@/src/features/filters/components/filter-builder";
+import { RouterOutputs, api } from "@/src/utils/api";
+import { FilterState, singleFilter } from "@langfuse/shared";
+import { createColumnHelper } from "@tanstack/react-table";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
+import { z } from "zod";
export type EvalConfigRow = {
id: string;
+ status: string;
createdAt: string;
- evalTemplateId?: string;
+ template?: string;
scoreName: string;
- targetObject: string;
- filter: string;
- variableMapping: string;
+ filter: FilterState;
};
export default function EvalConfigTable({ projectId }: { projectId: string }) {
@@ -28,63 +31,63 @@ export default function EvalConfigTable({ projectId }: { projectId: string }) {
});
const totalCount = templates.data?.totalCount ?? 0;
- const columns: LangfuseColumnDef<EvalConfigRow>[] = [
- {
- accessorKey: "id",
+ const columnHelper = createColumnHelper<EvalConfigRow>();
+ const columns = [
+ columnHelper.accessor("id", {
+ header: "Id",
id: "id",
- header: "ID",
- enableHiding: false,
- },
- {
- accessorKey: "createdAt",
+ cell: (row) => {
+ const id = row.getValue();
+ return id ? (
+ <TableLink
+ path={`/project/${projectId}/evals/configs/${encodeURIComponent(id)}`}
+ value={id}
+ truncateAt={50}
+ />
+ ) : undefined;
+ },
+ }),
+ columnHelper.accessor("status", {
+ id: "state",
+ header: "State",
+ }),
+ columnHelper.accessor("createdAt", {
id: "createdAt",
header: "Created At",
- enableHiding: true,
- },
- {
- accessorKey: "evalTemplateId",
- id: "evalTemplateId",
- header: "Eval Template",
- enableHiding: true,
- },
- {
- accessorKey: "scoreName",
+ }),
+ columnHelper.accessor("template", {
+ id: "template",
+ header: "Template",
+ }),
+ columnHelper.accessor("scoreName", {
id: "scoreName",
header: "Score Name",
- enableHiding: true,
- },
- {
- accessorKey: "targetObject",
- id: "targetObject",
- header: "Target",
- enableHiding: true,
- },
- {
- accessorKey: "filter",
+ }),
+ columnHelper.accessor("filter", {
id: "filter",
header: "Filter",
- enableHiding: true,
- },
- {
- accessorKey: "variableMapping",
- id: "variableMapping",
- header: "Mapping",
- enableHiding: true,
- },
- ];
+ cell: (row) => {
+ const node = row.getValue();
+ return <InlineFilterState filterState={node} />;
+ },
+ }),
+ ] as LangfuseColumnDef<EvalConfigRow>[];
const [columnVisibility, setColumnVisibility] =
useColumnVisibility<EvalConfigRow>("evalConfigColumnVisibility", columns);
- const convertToTableRow = (jobConfig: JobConfiguration): EvalConfigRow => {
+ const convertToTableRow = (
+ jobConfig: RouterOutputs["evals"]["allConfigs"]["configs"][number],
+ ): EvalConfigRow => {
return {
id: jobConfig.id,
+ status: jobConfig.status,
createdAt: jobConfig.createdAt.toLocaleString(),
- evalTemplateId: jobConfig.evalTemplateId?.toLocaleString(),
+ template: jobConfig.evalTemplate
+ ? `${jobConfig.evalTemplate.name} (v${jobConfig.evalTemplate.version})`
+ : undefined,
scoreName: jobConfig.scoreName,
- targetObject: jobConfig.targetObject,
- filter: JSON.stringify(jobConfig.filter),
- variableMapping: JSON.stringify(jobConfig.variableMapping),
+ filter: z.array(singleFilter).parse(jobConfig.filter),
};
};
diff --git a/web/src/features/evals/components/eval-template-detail.tsx b/web/src/features/evals/components/eval-template-detail.tsx
index f99ccf6975..ea70d57489 100644
--- a/web/src/features/evals/components/eval-template-detail.tsx
+++ b/web/src/features/evals/components/eval-template-detail.tsx
@@ -1,6 +1,6 @@
import * as React from "react";
import Header from "@/src/components/layouts/header";
-import { EvalTemplateForm } from "@/src/features/evals/components/new-template-form";
+import { EvalTemplateForm } from "@/src/features/evals/components/template-form";
import { PlaygroundProvider } from "@/src/features/playground/client/context";
import { api } from "@/src/utils/api";
import { EvalTemplate, evalModels } from "@langfuse/shared";
@@ -49,11 +49,6 @@ export const EvalTemplateDetail = () => {
<div className="md:container">
<Header
title={template.data?.name ?? "Loading..."}
- help={{
- description:
- "A scores is an evaluation of a traces or observations. It can be created from user feedback, model-based evaluations, or manual review. See docs to learn more.",
- href: "https://langfuse.com/docs/scores",
- }}
actionButtons={
template.data && (
<>
diff --git a/web/src/features/evals/components/new-eval-config-form.tsx b/web/src/features/evals/components/new-eval-config-form.tsx
deleted file mode 100644
index 27c456b425..0000000000
--- a/web/src/features/evals/components/new-eval-config-form.tsx
+++ /dev/null
@@ -1,423 +0,0 @@
-import { usePostHog } from "posthog-js/react";
-import { useFieldArray, useForm } from "react-hook-form";
-import { Input } from "@/src/components/ui/input";
-import { Button } from "@/src/components/ui/button";
-import {
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@/src/components/ui/form";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/src/components/ui/select";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
-import { tracesTableColsWithOptions, singleFilter } from "@langfuse/shared";
-import { type FilterState } from "@langfuse/shared";
-import * as z from "zod";
-import { Card } from "@/src/components/ui/card";
-import { useEffect, useState } from "react";
-import { api } from "@/src/utils/api";
-import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";
-import {
- type EvalTemplate,
- variableMapping,
- wipVariableMapping,
- evalObjects,
-} from "@langfuse/shared";
-import router from "next/router";
-
-const formSchema = z.object({
- evalTemplateId: z.string(),
- scoreName: z.string(),
- target: z.string(),
- filter: z.array(singleFilter).nullable(), // re-using the filter type from the tables
- mapping: z.array(wipVariableMapping),
- sampling: z.coerce.number().gte(0).lte(1),
- delay: z.coerce.number().optional().default(10_000),
-});
-
-export const NewEvalConfigForm = (props: {
- projectId: string;
- evalTemplates: EvalTemplate[];
- onFormSuccess?: () => void;
-}) => {
- const [formError, setFormError] = useState<string | null>(null);
- const posthog = usePostHog();
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
- defaultValues: {
- evalTemplateId: "",
- scoreName: undefined,
- target: "trace",
- filter: [] as FilterState,
- mapping: [],
- sampling: 1,
- delay: 10_000,
- },
- });
-
- const traceFilterOptions = api.traces.filterOptions.useQuery({
- projectId: props.projectId,
- ...form.getFieldState("filter"),
- });
-
- const getSelectedEvalTemplate = props.evalTemplates.find(
- (template) =>
- `${template.name}-${template.version}` ===
- form.getValues().evalTemplateId,
- );
-
- useEffect(() => {
- if (getSelectedEvalTemplate) {
- form.setValue("mapping", []);
- form.setValue(
- "mapping",
- getSelectedEvalTemplate.vars.map((v) => ({
- templateVariable: v,
- langfuseObject: "trace" as const,
- })),
- );
- }
- }, [form, getSelectedEvalTemplate]);
-
- const { fields } = useFieldArray({
- control: form.control,
- name: "mapping",
- });
-
- const utils = api.useUtils();
- const createJobMutation = api.evals.createJob.useMutation({
- onSuccess: () => utils.models.invalidate(),
- onError: (error) => setFormError(error.message),
- });
-
- function onSubmit(values: z.infer<typeof formSchema>) {
- posthog.capture("models:new_template_form");
- if (!getSelectedEvalTemplate) {
- setFormError("Please select an eval template");
- return;
- }
-
- // validate wip variable mapping
- const validatedVarMapping = z.array(variableMapping).parse(values.mapping);
-
- createJobMutation
- .mutateAsync({
- projectId: props.projectId,
- evalTemplateId: getSelectedEvalTemplate.id,
- scoreName: values.scoreName,
- target: values.target,
- filter: values.filter,
- mapping: validatedVarMapping,
- sampling: values.sampling,
- })
- .then(() => {
- props.onFormSuccess?.();
- form.reset();
- void router.push(`/project/${props.projectId}/evals/configs/`);
- })
- .catch((error) => {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- if ("message" in error && typeof error.message === "string") {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- setFormError(error.message as string);
- return;
- } else {
- setFormError(JSON.stringify(error));
- console.error(error);
- }
- });
- }
-
- return (
- <Form {...form}>
- {JSON.stringify(form.watch(), null, 2)}
- <form
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
- onSubmit={form.handleSubmit(onSubmit)}
- className="flex flex-col gap-4"
- >
- <div className="grid gap-4">
- <FormField
- control={form.control}
- name="evalTemplateId"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Eval Template</FormLabel>
- <Select
- defaultValue={field.value}
- onValueChange={(value) => {
- field.onChange(value);
- }}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue placeholder="Select a model to run this eval template" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {props.evalTemplates.map((template) => (
- <SelectItem
- value={`${template.name}-${template.version}`}
- key={template.id}
- >
- {`${template.name}-${template.version}`}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="scoreName"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Score Name</FormLabel>
- <FormControl>
- <Input {...field} />
- </FormControl>
- <FormDescription>
- Optional score name, defaults to ABCDEFG
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <Card className="p-4">
- <FormField
- control={form.control}
- name="target"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Eval target object</FormLabel>
- <FormControl>
- <Tabs defaultValue="trace">
- <TabsList {...field}>
- <TabsTrigger value="trace">Trace</TabsTrigger>
- <TabsTrigger value="observation" disabled={true}>
- Observation (coming soon)
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </FormControl>
- <FormDescription>Description</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </Card>
- <Card className="p-4">
- <FormField
- control={form.control}
- name="filter"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Target filter</FormLabel>
- <FormControl>
- <div className="w-1/2">
- <InlineFilterBuilder
- columns={tracesTableColsWithOptions(
- traceFilterOptions.data,
- )}
- filterState={field.value ?? []}
- onChange={(value) => field.onChange(value)}
- />
- </div>
- </FormControl>
- <FormDescription>
- This will run on all future and XX historical traces.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </Card>
-
- <Card className="p-4">
- <FormLabel>Variable mapping</FormLabel>
- <FormControl>Here will some variable mapping be added.</FormControl>
- <div className="mt-2 flex flex-col gap-2">
- {fields.map((mappingField, index) => (
- <div className="flex gap-2" key={index}>
- <span className="whitespace-nowrap rounded-md bg-slate-200 px-2 py-1 text-xs ">
- {mappingField.templateVariable}
- </span>
- <FormField
- control={form.control}
- key={`${mappingField.id}-langfuseObject`}
- name={`mapping.${index}.langfuseObject`}
- render={({ field }) => (
- <FormItem>
- <FormControl>
- <Select
- defaultValue={
- evalObjects.find(
- (evalObject) => evalObject.id === field.value,
- )?.display
- }
- onValueChange={(value) => {
- const obj = evalObjects.find(
- (evalObject) => evalObject.display === value,
- );
- field.onChange(obj?.id);
- }}
- >
- <SelectTrigger>
- <SelectValue placeholder="Object type" />
- </SelectTrigger>
- <SelectContent>
- {evalObjects.map((evalObject) => (
- <SelectItem
- value={evalObject.display}
- key={evalObject.id}
- >
- {evalObject.display}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- {form.watch(`mapping.${index}.langfuseObject`) !== "trace" ? (
- <FormField
- control={form.control}
- key={`${mappingField.id}-objectName`}
- name={`mapping.${index}.objectName`}
- render={({ field }) => (
- <FormItem>
- <FormControl>
- <Input {...field} value={field.value ?? ""} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- ) : undefined}
-
- <FormField
- control={form.control}
- key={`${mappingField.id}-selectedColumnId`}
- name={`mapping.${index}.selectedColumnId`}
- render={({ field }) => (
- <FormItem>
- <FormControl>
- <Select
- defaultValue={
- field.value
- ? evalObjects.find(
- (evalObject) =>
- evalObject.id === field.value,
- )?.availableColumns[0].name ?? "N/A"
- : "N/A"
- }
- onValueChange={(value) => {
- const availableColumns = evalObjects.find(
- (evalObject) =>
- evalObject.id ===
- form.watch(`mapping.${index}.langfuseObject`),
- )?.availableColumns;
- const column = availableColumns?.find(
- (column) => column.name === value,
- );
-
- field.onChange(column?.id);
- }}
- >
- <SelectTrigger>
- <SelectValue placeholder="Object type" />
- </SelectTrigger>
- <SelectContent>
- {evalObjects
- .find(
- (evalObject) =>
- evalObject.id ===
- form.watch(
- `mapping.${index}.langfuseObject`,
- ),
- )
- ?.availableColumns.map((column) => (
- <SelectItem
- value={column.name}
- key={column.id}
- >
- {column.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- ))}
- </div>
- <FormDescription>Description </FormDescription>
- <FormMessage />
- </Card>
- <Card className="p-4">
- <FormField
- control={form.control}
- name="sampling"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Sampling</FormLabel>
- <FormControl>
- <Input {...field} />
- </FormControl>
- <FormDescription>Description </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="delay"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Delay (ms)</FormLabel>
- <FormControl>
- <Input {...field} />
- </FormControl>
- <FormDescription>Description </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </Card>
- </div>
-
- <Button
- type="submit"
- loading={createJobMutation.isLoading}
- className="mt-3"
- >
- Save
- </Button>
- </form>
- {formError ? (
- <p className="text-red text-center">
- <span className="font-bold">Error:</span> {formError}
- </p>
- ) : null}
- </Form>
- );
-};
diff --git a/web/src/features/evals/components/new-template-form.tsx b/web/src/features/evals/components/template-form.tsx
similarity index 98%
rename from web/src/features/evals/components/new-template-form.tsx
rename to web/src/features/evals/components/template-form.tsx
index 5e9410beb9..eaab0091df 100644
--- a/web/src/features/evals/components/new-template-form.tsx
+++ b/web/src/features/evals/components/template-form.tsx
@@ -23,10 +23,9 @@ import { usePlaygroundContext } from "@/src/features/playground/client/context";
import { ModelParameters } from "@/src/features/playground/client/components/ModelParameters";
import { EvalModelNames, OutputSchema, evalModels } from "@langfuse/shared";
import { PromptDescription } from "@/src/features/prompts/components/prompt-description";
-import { AlphaNumericUnderscoreString } from "@/src/utils/zod";
const formSchema = z.object({
- name: AlphaNumericUnderscoreString,
+ name: z.string().min(1, "Enter a name"),
prompt: z
.string()
.min(1, "Enter a prompt")
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index 9601d33761..82378b346b 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -13,10 +13,9 @@ import {
singleFilter,
variableMapping,
} from "@langfuse/shared";
-import { AlphaNumericUnderscoreString } from "@/src/utils/zod";
export const CreateEvalTemplate = z.object({
- name: AlphaNumericUnderscoreString,
+ name: z.string().min(1),
projectId: z.string(),
prompt: z.string(),
model: EvalModelNames,
@@ -49,6 +48,9 @@ export const evalRouter = createTRPCRouter({
projectId: input.projectId,
jobType: "EVAL",
},
+ include: {
+ evalTemplate: true,
+ },
take: input.limit,
skip: input.page * input.limit,
});
@@ -65,6 +67,33 @@ export const evalRouter = createTRPCRouter({
};
}),
+ configById: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ id: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "job:read",
+ });
+
+ const config = await ctx.prisma.jobConfiguration.findUnique({
+ where: {
+ id: input.id,
+ projectId: input.projectId,
+ },
+ include: {
+ evalTemplate: true,
+ },
+ });
+
+ return config;
+ }),
+
allTemplatesForName: protectedProjectProcedure
.input(
z.object({
@@ -195,7 +224,7 @@ export const evalRouter = createTRPCRouter({
z.object({
projectId: z.string(),
evalTemplateId: z.string(),
- scoreName: AlphaNumericUnderscoreString,
+ 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),
@@ -208,7 +237,7 @@ export const evalRouter = createTRPCRouter({
throwIfNoAccess({
session: ctx.session,
projectId: input.projectId,
- scope: "job:create",
+ scope: "job:CUD",
});
const evalTemplate = await ctx.prisma.evalTemplate.findUnique({
@@ -236,6 +265,7 @@ export const evalRouter = createTRPCRouter({
variableMapping: input.mapping,
sampling: input.sampling,
delay: DEFAULT_TRACE_JOB_DELAY, // 10 seconds default
+ status: "ACTIVE",
},
});
await auditLog({
@@ -287,4 +317,37 @@ export const evalRouter = createTRPCRouter({
});
return evalTemplate;
}),
+
+ updateEvalJob: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ evalConfigId: z.string(),
+ updatedStatus: z.enum(["ACTIVE", "INACTIVE"]),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "job:CUD",
+ });
+
+ await ctx.prisma.jobConfiguration.update({
+ where: {
+ id: input.evalConfigId,
+ projectId: input.projectId,
+ },
+ data: {
+ status: input.updatedStatus,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "job",
+ resourceId: input.evalConfigId,
+ action: "update",
+ });
+ }),
});
diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsx
index d6a3e2828a..59043dda80 100644
--- a/web/src/features/filters/components/filter-builder.tsx
+++ b/web/src/features/filters/components/filter-builder.tsx
@@ -87,36 +87,9 @@ export function PopoverFilterBuilder({
<Button variant="outline">
<Filter className="h-4 w-4" />
<span className="hidden lg:ml-2 lg:inline">Filter</span>
- {filterState.length > 0 && filterState.length < 3
- ? filterState.map((filter, i) => {
- return (
- <span
- key={i}
- className="ml-2 hidden whitespace-nowrap rounded-md bg-slate-200 px-2 py-1 text-xs lg:block"
- >
- {filter.column}
- {filter.type === "stringObject" ||
- filter.type === "numberObject"
- ? `.${filter.key}`
- : ""}{" "}
- {filter.operator}{" "}
- {filter.type === "datetime"
- ? new Date(filter.value).toLocaleDateString()
- : filter.type === "stringOptions" ||
- filter.type === "arrayOptions"
- ? filter.value.length > 2
- ? `${filter.value.length} selected`
- : filter.value.join(", ")
- : filter.type === "number" ||
- filter.type === "numberObject"
- ? filter.value
- : filter.type === "boolean"
- ? `${filter.value}`
- : `"${filter.value}"`}
- </span>
- );
- })
- : null}
+ {filterState.length > 0 && filterState.length < 3 ? (
+ <InlineFilterState filterState={filterState} />
+ ) : null}
{filterState.length > 0 && (
<span
className={cn(
@@ -154,14 +127,48 @@ export function PopoverFilterBuilder({
);
}
+export function InlineFilterState({
+ filterState,
+}: {
+ filterState: FilterState;
+}) {
+ return filterState.map((filter, i) => {
+ return (
+ <span
+ key={i}
+ className="ml-2 hidden whitespace-nowrap rounded-md bg-slate-200 px-2 py-1 text-xs lg:block"
+ >
+ {filter.column}
+ {filter.type === "stringObject" || filter.type === "numberObject"
+ ? `.${filter.key}`
+ : ""}{" "}
+ {filter.operator}{" "}
+ {filter.type === "datetime"
+ ? new Date(filter.value).toLocaleDateString()
+ : filter.type === "stringOptions" || filter.type === "arrayOptions"
+ ? filter.value.length > 2
+ ? `${filter.value.length} selected`
+ : filter.value.join(", ")
+ : filter.type === "number" || filter.type === "numberObject"
+ ? filter.value
+ : filter.type === "boolean"
+ ? `${filter.value}`
+ : `"${filter.value}"`}
+ </span>
+ );
+ });
+}
+
export function InlineFilterBuilder({
columns,
filterState,
onChange,
+ disabled,
}: {
columns: ColumnDefinition[];
filterState: FilterState;
onChange: Dispatch<SetStateAction<FilterState>>;
+ disabled?: boolean;
}) {
const [wipFilterState, _setWipFilterState] =
useState<WipFilterState>(filterState);
@@ -185,6 +192,7 @@ export function InlineFilterBuilder({
columns={columns}
filterState={wipFilterState}
onChange={setWipFilterState}
+ disabled={disabled}
/>
</div>
);
@@ -194,10 +202,12 @@ function FilterBuilderForm({
columns,
filterState,
onChange,
+ disabled,
}: {
columns: ColumnDefinition[];
filterState: WipFilterState;
onChange: Dispatch<SetStateAction<WipFilterState>>;
+ disabled?: boolean;
}) {
const handleFilterChange = (filter: WipFilterCondition, i: number) => {
onChange((prev) => {
@@ -243,6 +253,7 @@ function FilterBuilderForm({
{/* selector of the column to be filtered */}
<Select
value={column ? column.id : ""}
+ disabled={disabled}
onValueChange={(value) => {
handleFilterChange(
{
@@ -298,6 +309,7 @@ function FilterBuilderForm({
<Input
value={filter.key ?? ""}
placeholder="key"
+ disabled={disabled}
onChange={(e) =>
handleFilterChange(
{ ...filter, key: e.target.value },
@@ -310,7 +322,7 @@ function FilterBuilderForm({
</td>
<td className="p-1">
<Select
- disabled={!filter.column}
+ disabled={!filter.column || disabled}
onValueChange={(value) => {
handleFilterChange(
{
@@ -341,6 +353,7 @@ function FilterBuilderForm({
{filter.type === "string" ||
filter.type === "stringObject" ? (
<Input
+ disabled={disabled}
value={filter.value ?? ""}
placeholder="string"
onChange={(e) =>
@@ -354,6 +367,7 @@ function FilterBuilderForm({
filter.type === "numberObject" ? (
<Input
value={filter.value ?? undefined}
+ disabled={disabled}
type="number"
step="0.01"
lang="en-US"
@@ -372,6 +386,7 @@ function FilterBuilderForm({
) : filter.type === "datetime" ? (
<DatePicker
className="min-w-[100px]"
+ disabled={disabled}
date={filter.value ? new Date(filter.value) : undefined}
onChange={(date) => {
handleFilterChange(
@@ -395,9 +410,11 @@ function FilterBuilderForm({
handleFilterChange({ ...filter, value }, i)
}
values={Array.isArray(filter.value) ? filter.value : []}
+ disabled={disabled}
/>
) : filter.type === "boolean" ? (
<Select
+ disabled={disabled}
onValueChange={(value) => {
handleFilterChange(
{
@@ -429,6 +446,7 @@ function FilterBuilderForm({
<Button
onClick={() => removeFilter(i)}
variant="ghost"
+ disabled={disabled}
size="xs"
>
<X className="h-4 w-4" />
@@ -439,18 +457,18 @@ function FilterBuilderForm({
})}
</tbody>
</table>
- <Button
- onClick={() => addNewFilter()}
- className="mt-2"
- variant="ghost"
- size="sm"
- >
- <Plus className="mr-2 h-4 w-4" />
- Add filter
- </Button>
- {/* <pre>
- <code>{JSON.stringify(filterState, null, 2)}</code>
- </pre> */}
+ {!disabled ? (
+ <Button
+ onClick={() => addNewFilter()}
+ type="button" // required as it will otherwise submit forms where this component is used
+ className="mt-2"
+ variant="ghost"
+ size="sm"
+ >
+ <Plus className="mr-2 h-4 w-4" />
+ Add filter
+ </Button>
+ ) : null}
</>
);
}
diff --git a/web/src/features/filters/components/multi-select.tsx b/web/src/features/filters/components/multi-select.tsx
index 533c6f63c1..b0cd913d03 100644
--- a/web/src/features/filters/components/multi-select.tsx
+++ b/web/src/features/filters/components/multi-select.tsx
@@ -27,12 +27,14 @@ export function MultiSelect({
onValueChange,
options,
className,
+ disabled,
}: {
title?: string;
values: string[];
onValueChange: (values: string[]) => void;
options: FilterOption[] | readonly FilterOption[];
className?: string;
+ disabled?: boolean;
}) {
const selectedValues = new Set(values);
@@ -45,6 +47,7 @@ export function MultiSelect({
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-transparent px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
+ disabled={disabled}
>
Select
<ChevronDown className="h-4 w-4 opacity-50" />
diff --git a/web/src/features/rbac/constants/roleAccessRights.ts b/web/src/features/rbac/constants/roleAccessRights.ts
index 1dc8ef06fa..b63696275c 100644
--- a/web/src/features/rbac/constants/roleAccessRights.ts
+++ b/web/src/features/rbac/constants/roleAccessRights.ts
@@ -30,10 +30,8 @@ const scopes = [
"evalTemplate:create",
"evalTemplate:read",
- "evalConfig:create",
- "evalConfig:read",
"job:read",
- "job:create",
+ "job:CUD",
] as const;
// type string of all Resource:Action, e.g. "members:read"
@@ -61,10 +59,8 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"models:CUD",
"evalTemplate:create",
"evalTemplate:read",
- "evalConfig:create",
- "evalConfig:read",
+ "job:CUD",
"job:read",
- "job:create",
],
ADMIN: [
"project:update",
@@ -85,10 +81,8 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"models:CUD",
"evalTemplate:create",
"evalTemplate:read",
- "evalConfig:create",
- "evalConfig:read",
+ "job:CUD",
"job:read",
- "job:create",
],
MEMBER: [
"members:read",
@@ -101,9 +95,8 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"prompts:read",
"evalTemplate:create",
"evalTemplate:read",
- "evalConfig:read",
"job:read",
- "job:create",
+ "job:CUD",
],
VIEWER: ["prompts:read"],
};
diff --git a/web/src/pages/project/[projectId]/evals/configs/[configId].tsx b/web/src/pages/project/[projectId]/evals/configs/[configId].tsx
new file mode 100644
index 0000000000..bc62614b91
--- /dev/null
+++ b/web/src/pages/project/[projectId]/evals/configs/[configId].tsx
@@ -0,0 +1,3 @@
+import { EvalConfigDetail } from "@/src/features/evals/components/eval-config-detail";
+
+export default EvalConfigDetail;
diff --git a/web/src/pages/project/[projectId]/evals/configs/index.tsx b/web/src/pages/project/[projectId]/evals/configs/index.tsx
index 11b8f5ac47..b83d6f0852 100644
--- a/web/src/pages/project/[projectId]/evals/configs/index.tsx
+++ b/web/src/pages/project/[projectId]/evals/configs/index.tsx
@@ -17,7 +17,7 @@ export default function ConfigsPage() {
const hasWriteAccess = useHasAccess({
projectId,
- scope: "evalConfig:create",
+ scope: "job:CUD",
});
return (
diff --git a/web/src/pages/project/[projectId]/evals/configs/new.tsx b/web/src/pages/project/[projectId]/evals/configs/new.tsx
index 6df1b1370f..c3bbae76fe 100644
--- a/web/src/pages/project/[projectId]/evals/configs/new.tsx
+++ b/web/src/pages/project/[projectId]/evals/configs/new.tsx
@@ -1,5 +1,5 @@
import Header from "@/src/components/layouts/header";
-import { NewEvalConfigForm } from "@/src/features/evals/components/new-eval-config-form";
+import { EvalConfigForm } from "@/src/features/evals/components/eval-config-form";
import { api } from "@/src/utils/api";
import { useRouter } from "next/router";
@@ -16,15 +16,8 @@ export default function NewConfigsPage() {
return (
<div>
- <Header
- title="Create eval config"
- help={{
- description:
- "A scores is an evaluation of a traces or observations. It can be created from user feedback, model-based evaluations, or manual review. See docs to learn more.",
- href: "https://langfuse.com/docs/scores",
- }}
- />
- <NewEvalConfigForm
+ <Header title="Create eval config" />
+ <EvalConfigForm
projectId={projectId}
evalTemplates={evalTemplates.data?.templates ?? []}
/>
diff --git a/web/src/pages/project/[projectId]/evals/templates/new.tsx b/web/src/pages/project/[projectId]/evals/templates/new.tsx
index bbed868e7a..14c5fbe7c9 100644
--- a/web/src/pages/project/[projectId]/evals/templates/new.tsx
+++ b/web/src/pages/project/[projectId]/evals/templates/new.tsx
@@ -1,5 +1,5 @@
import Header from "@/src/components/layouts/header";
-import { EvalTemplateForm } from "@/src/features/evals/components/new-template-form";
+import { EvalTemplateForm } from "@/src/features/evals/components/template-form";
import { PlaygroundProvider } from "@/src/features/playground/client/context";
import { api } from "@/src/utils/api";
import { evalModels } from "@langfuse/shared";
@@ -12,14 +12,7 @@ export default function NewTemplatesPage() {
return (
<div className="md:container">
- <Header
- title="Create eval template"
- help={{
- description:
- "A scores is an evaluation of a traces or observations. It can be created from user feedback, model-based evaluations, or manual review. See docs to learn more.",
- href: "https://langfuse.com/docs/scores",
- }}
- />
+ <Header title="Create eval template" />
<PlaygroundProvider avilableModels={[...evalModels]}>
<EvalTemplateForm projectId={projectId} isEditing={true} />
</PlaygroundProvider>
diff --git a/web/src/utils/zod.ts b/web/src/utils/zod.ts
index ef05acc3d2..eae55d84ff 100644
--- a/web/src/utils/zod.ts
+++ b/web/src/utils/zod.ts
@@ -53,8 +53,3 @@ export const noHtmlRegex = /<[^>]*>/;
export const noHtmlCheck = (value: string) => !noHtmlRegex.test(value);
export const NonEmptyString = z.string().min(1);
-
-export const AlphaNumericUnderscoreString = z
- .string()
- .min(1, "Enter a name")
- .regex(/^[A-Za-z_]+$/, "Must be alphanumeric or contain dashes (_)");