Skip to content

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

feat: templates evals UI (#1654)

Max Deichmann02361ea10cf9
diff --git a/packages/shared/src/server/evals/types.ts b/packages/shared/src/server/evals/types.ts
index 6a5e97f361..bc92b8c9ca 100644
--- a/packages/shared/src/server/evals/types.ts
+++ b/packages/shared/src/server/evals/types.ts
@@ -53,6 +53,25 @@ export const evalModels = [
max_tokens: 256,
top_p: 1,
},
+ {
+ provider: ModelProvider.OpenAI,
+ model: "gpt-4-turbo-preview",
+ temperature: 1,
+ maxTemperature: 2,
+ max_tokens: 256,
+ top_p: 1,
+ },
] as const;
-export const EvalModelNames = z.enum(["gpt-3.5-turbo"]);
+export const EvalModelNames = z.enum(["gpt-3.5-turbo", "gpt-4-turbo-preview"]);
+
+export const OutputSchema = z.object({
+ reasoning: z.string(),
+ score: z.string(),
+});
+
+export enum EvalTargetObject {
+ Trace = "trace",
+}
+
+export const DEFAULT_TRACE_JOB_DELAY = 10_000;
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index 3f3670c5ae..d99b4c3aa0 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -84,6 +84,8 @@ export async function fetchLLMCompletion(
});
}
+ console.log("Making LLM call with params: ", modelParams);
+
if (params.functionCall) {
const functionCallingModel = chatModel.bind({
functions: [
diff --git a/web/src/features/evals/components/eval-template-detail.tsx b/web/src/features/evals/components/eval-template-detail.tsx
new file mode 100644
index 0000000000..f99ccf6975
--- /dev/null
+++ b/web/src/features/evals/components/eval-template-detail.tsx
@@ -0,0 +1,160 @@
+import * as React from "react";
+import Header from "@/src/components/layouts/header";
+import { EvalTemplateForm } from "@/src/features/evals/components/new-template-form";
+import { PlaygroundProvider } from "@/src/features/playground/client/context";
+import { api } from "@/src/utils/api";
+import { EvalTemplate, evalModels } from "@langfuse/shared";
+import router, { useRouter } from "next/router";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { Button } from "@/src/components/ui/button";
+import { Pencil } from "lucide-react";
+import { useState } from "react";
+
+export const EvalTemplateDetail = () => {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const templateId = router.query.id as string;
+
+ const [isEditing, setIsEditing] = useState(false);
+
+ // get the current template by id
+ const template = api.evals.templateById.useQuery({
+ projectId: projectId,
+ id: templateId,
+ });
+
+ // get all templates for the current template name
+ const allTemplates = api.evals.allTemplatesForName.useQuery(
+ {
+ projectId: projectId,
+ name: template.data?.name ?? "",
+ },
+ {
+ enabled:
+ !template.isLoading &&
+ !template.isError &&
+ template.data?.name !== undefined,
+ },
+ );
+
+ return (
+ <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 && (
+ <>
+ {!isEditing && (
+ <UpdateTemplate
+ projectId={projectId}
+ isLoading={template.isLoading}
+ setIsEditing={setIsEditing}
+ />
+ )}
+ <EvalVersionDropdown
+ disabled={allTemplates.isLoading}
+ options={allTemplates.data?.templates ?? []}
+ defaultOption={template.data ?? undefined}
+ onSelect={(template) => {
+ router.push(
+ `/project/${projectId}/evals/templates/${template.id}`,
+ );
+ }}
+ />
+ </>
+ )
+ }
+ />
+ {allTemplates.isLoading || !allTemplates.data ? (
+ <div>Loading...</div>
+ ) : (
+ <PlaygroundProvider avilableModels={[...evalModels]}>
+ <EvalTemplateForm
+ projectId={projectId}
+ existingEvalTemplate={template.data ?? undefined}
+ isEditing={isEditing}
+ setIsEditing={setIsEditing}
+ />
+ </PlaygroundProvider>
+ )}
+ </div>
+ );
+};
+
+export function EvalVersionDropdown(props: {
+ disabled: boolean;
+ options?: EvalTemplate[];
+ defaultOption?: EvalTemplate;
+ onSelect?: (template: EvalTemplate) => void;
+}) {
+ const handleSelect = (value: string) => {
+ const selectedTemplate = props.options?.find(
+ (template) => template.id === value,
+ );
+ if (selectedTemplate && props.onSelect) {
+ props.onSelect(selectedTemplate);
+ }
+ };
+
+ return (
+ <Select
+ disabled={props.disabled}
+ onValueChange={handleSelect}
+ defaultValue={props.defaultOption ? props.defaultOption.id : undefined}
+ >
+ <SelectTrigger className="w-[180px]">
+ <SelectValue placeholder="Version" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectGroup>
+ {props.options?.map((template) => (
+ <SelectItem key={template.id} value={template.id}>
+ {template.version} - {template.createdAt.toLocaleDateString()}
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ </SelectContent>
+ </Select>
+ );
+}
+
+export function UpdateTemplate({
+ projectId,
+ isLoading,
+ setIsEditing,
+}: {
+ projectId: string;
+ isLoading: boolean;
+ setIsEditing: (isEditing: boolean) => void;
+}) {
+ const hasAccess = useHasAccess({ projectId, scope: "evalTemplate:create" });
+
+ const handlePromptEdit = () => {
+ setIsEditing(true);
+ };
+
+ return (
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => handlePromptEdit()}
+ disabled={!hasAccess}
+ loading={isLoading}
+ >
+ <Pencil className="h-5 w-5" />
+ </Button>
+ );
+}
diff --git a/web/src/features/evals/components/eval-templates-table.tsx b/web/src/features/evals/components/eval-templates-table.tsx
index bd0c758728..20c0a17b1b 100644
--- a/web/src/features/evals/components/eval-templates-table.tsx
+++ b/web/src/features/evals/components/eval-templates-table.tsx
@@ -1,20 +1,16 @@
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 EvalTemplate } from "@prisma/client";
+import { RouterOutputs, api } from "@/src/utils/api";
+import { createColumnHelper } from "@tanstack/react-table";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
export type EvalsTemplateRow = {
- version: number;
name: string;
- prompt: string;
- model: string;
- modelParameters: unknown;
- variables: string[];
- outputScore?: string;
- outputName?: string;
- outputReasoning?: string;
+ latestCreatedAt?: Date;
+ latestVersion?: number;
+ latestId?: string;
};
export default function EvalsTemplateTable({
@@ -27,103 +23,66 @@ export default function EvalsTemplateTable({
pageSize: withDefault(NumberParam, 50),
});
- const templates = api.evals.allTemplates.useQuery({
+ const templates = api.evals.templateNames.useQuery({
+ projectId,
page: paginationState.pageIndex,
limit: paginationState.pageSize,
- projectId,
});
const totalCount = templates.data?.totalCount ?? 0;
- const columns: LangfuseColumnDef<EvalsTemplateRow>[] = [
- {
- accessorKey: "name",
- header: "Name",
- enableHiding: true,
- },
- {
- accessorKey: "version",
- header: "Version",
- enableHiding: true,
- },
- {
- accessorKey: "prompt",
- header: "Prompt",
- enableHiding: true,
- },
- {
- accessorKey: "model",
- header: "Model",
- enableHiding: true,
- },
- {
- accessorKey: "modelParameters",
- header: "Model Parameters",
- enableHiding: true,
- },
- {
- accessorKey: "variables",
- header: "Variables",
- enableHiding: true,
- },
- {
- accessorKey: "score",
- header: "Score",
- enableHiding: true,
- },
- {
- accessorKey: "name",
+ const columnHelper = createColumnHelper<EvalsTemplateRow>();
+
+ const columns = [
+ columnHelper.accessor("name", {
header: "Name",
- enableHiding: true,
- },
- {
- accessorKey: "reasoning",
- header: "Reasoning",
- enableHiding: true,
- },
- ];
+ id: "name",
+ cell: (row) => {
+ const name = row.getValue();
+ const id = row.row.original.latestId;
+
+ if (!id) {
+ return name;
+ }
+
+ return name ? (
+ <TableLink
+ path={`/project/${projectId}/evals/templates/${encodeURIComponent(id)}`}
+ value={name}
+ truncateAt={50}
+ />
+ ) : undefined;
+ },
+ }),
+ columnHelper.accessor("latestCreatedAt", {
+ header: "Last Edit",
+ id: "latestCreatedAt",
+ cell: (row) => {
+ return row.getValue()?.toLocaleDateString();
+ },
+ }),
+ columnHelper.accessor("latestVersion", {
+ header: "Last Version",
+ id: "version",
+ cell: (row) => {
+ return row.getValue();
+ },
+ }),
+ ] as LangfuseColumnDef<EvalsTemplateRow>[];
const [columnVisibility, setColumnVisibility] =
useColumnVisibility<EvalsTemplateRow>(
- "evalTemplateConfigColumnVisibility",
+ "evalTemplatesColumnVisibility",
columns,
);
- const convertToTableRow = (template: EvalTemplate): EvalsTemplateRow => {
- if (
- typeof template.outputSchema !== "object" ||
- template.outputSchema === null
- ) {
- return {
- name: template.name,
- version: template.version,
- prompt: template.prompt,
- model: template.model,
- modelParameters: template.modelParams,
- variables: template.vars,
- };
- }
+ const convertToTableRow = (
+ template: RouterOutputs["evals"]["templateNames"]["templates"][number],
+ ): EvalsTemplateRow => {
return {
name: template.name,
- version: template.version,
- prompt: template.prompt,
- model: template.model,
- modelParameters: JSON.stringify(template.modelParams),
- variables: template.vars,
- outputScore:
- "scores" in template.outputSchema &&
- typeof template.outputSchema.scores === "string"
- ? template.outputSchema.scores
- : undefined,
- outputName:
- "name" in template.outputSchema &&
- typeof template.outputSchema.name === "string"
- ? template.outputSchema.name
- : undefined,
- outputReasoning:
- "reasoning" in template.outputSchema &&
- typeof template.outputSchema.reasoning === "string"
- ? template.outputSchema.reasoning
- : undefined,
+ latestCreatedAt: template.latestCreatedAt,
+ latestVersion: template.version,
+ latestId: template.latestId,
};
};
diff --git a/web/src/features/evals/components/new-template-form.tsx b/web/src/features/evals/components/new-template-form.tsx
index 88ffc5c11e..a5e6844f5d 100644
--- a/web/src/features/evals/components/new-template-form.tsx
+++ b/web/src/features/evals/components/new-template-form.tsx
@@ -1,5 +1,5 @@
import { usePostHog } from "posthog-js/react";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { Input } from "@/src/components/ui/input";
@@ -16,17 +16,17 @@ import {
import { Textarea } from "@/src/components/ui/textarea";
import { api } from "@/src/utils/api";
import { zodResolver } from "@hookform/resolvers/zod";
-import { extractVariables } from "@/src/utils/string";
-import { Badge } from "@/src/components/ui/badge";
+import { extractVariables, getIsCharOrUnderscore } from "@/src/utils/string";
import router from "next/router";
-import { AutoComplete } from "@/src/features/prompts/components/auto-complete";
import { type EvalTemplate } from "@prisma/client";
import { usePlaygroundContext } from "@/src/features/playground/client/context";
import { ModelParameters } from "@/src/features/playground/client/components/ModelParameters";
-import { EvalModelNames, evalModels } from "@langfuse/shared";
+import { EvalModelNames, OutputSchema, evalModels } from "@langfuse/shared";
+import { PromptDescription } from "@/src/features/prompts/components/prompt-description";
+import { AlphaNumericDashString } from "@/src/utils/zod";
const formSchema = z.object({
- name: z.string(),
+ name: AlphaNumericDashString,
prompt: z
.string()
.min(1, "Enter a prompt")
@@ -46,47 +46,74 @@ const formSchema = z.object({
z.string().min(1, "Variables must have at least one character"),
),
model: EvalModelNames,
- modelParameters: z.string().refine(
- (value) => {
- try {
- JSON.parse(value);
- return true;
- } catch (e) {
- return false;
- }
- },
- {
- message: "Config needs to be valid JSON",
- },
- ),
outputScore: z.string(),
- outputName: z.string(),
outputReasoning: z.string(),
});
-export const NewEvalTemplateForm = (props: {
+export const EvalTemplateForm = (props: {
projectId: string;
- existingEvalTemplates: EvalTemplate[];
+ existingEvalTemplate?: EvalTemplate;
onFormSuccess?: () => void;
+ isEditing?: boolean;
+ setIsEditing?: (isEditing: boolean) => void;
}) => {
const [formError, setFormError] = useState<string | null>(null);
+ const playgroundContext = usePlaygroundContext();
+
const posthog = usePostHog();
+
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
+ disabled: !props.isEditing,
defaultValues: {
- name: "",
- model: "gpt-3.5-turbo" as const,
- prompt: "",
- variables: [],
- modelParameters: "{}",
- outputName: "",
- outputScore: "",
- outputReasoning: "",
+ name: props.existingEvalTemplate?.name ?? "",
+ model: EvalModelNames.parse(
+ props.existingEvalTemplate?.model ?? "gpt-3.5-turbo",
+ ),
+ prompt: props.existingEvalTemplate?.prompt ?? undefined,
+ variables: props.existingEvalTemplate?.vars ?? [],
+ outputReasoning: props.existingEvalTemplate
+ ? OutputSchema.parse(props.existingEvalTemplate?.outputSchema).reasoning
+ : undefined,
+ outputScore: props.existingEvalTemplate
+ ? OutputSchema.parse(props.existingEvalTemplate?.outputSchema).score
+ : undefined,
},
});
- const playgroundContext = usePlaygroundContext();
- const extractedVariables = extractVariables(form.watch("prompt"));
+ // reset the form if the input template changes
+ useEffect(() => {
+ if (props.existingEvalTemplate) {
+ const model = EvalModelNames.parse(props.existingEvalTemplate.model);
+
+ form.reset({
+ name: props.existingEvalTemplate.name,
+ model: model,
+ prompt: props.existingEvalTemplate.prompt,
+ variables: props.existingEvalTemplate.vars,
+ outputReasoning: OutputSchema.parse(
+ props.existingEvalTemplate.outputSchema,
+ ).reasoning,
+ outputScore: OutputSchema.parse(props.existingEvalTemplate.outputSchema)
+ .score,
+ });
+
+ // also set the context for the playground
+ playgroundContext.updateModelParam("model", model);
+ playgroundContext.updateModelParams(
+ props.existingEvalTemplate.modelParams,
+ );
+
+ const modelProvider = evalModels.find((m) => m.model === model)?.provider;
+ if (modelProvider) {
+ playgroundContext.updateModelParam("provider", modelProvider);
+ }
+ }
+ }, [props.existingEvalTemplate, form]);
+
+ const extractedVariables = form.watch("prompt")
+ ? extractVariables(form.watch("prompt")).filter(getIsCharOrUnderscore)
+ : undefined;
const utils = api.useUtils();
const createEvalTemplateMutation = api.evals.createTemplate.useMutation({
@@ -95,6 +122,7 @@ export const NewEvalTemplateForm = (props: {
});
function onSubmit(values: z.infer<typeof formSchema>) {
+ console.log("submitting", values);
posthog.capture("models:new_template_form");
createEvalTemplateMutation
@@ -104,16 +132,19 @@ export const NewEvalTemplateForm = (props: {
prompt: values.prompt,
model: EvalModelNames.parse(playgroundContext.modelParams.model),
modelParameters: playgroundContext.modelParams,
- variables: extractedVariables,
+ variables: extractedVariables ?? [],
outputSchema: {
score: values.outputScore,
reasoning: values.outputReasoning,
},
})
- .then(() => {
+ .then((res) => {
props.onFormSuccess?.();
form.reset();
- void router.push(`/project/${props.projectId}/evals/templates/`);
+ props.setIsEditing?.(false);
+ void router.push(
+ `/project/${props.projectId}/evals/templates/${res.id}`,
+ );
})
.catch((error) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
@@ -133,121 +164,112 @@ export const NewEvalTemplateForm = (props: {
<form
// eslint-disable-next-line @typescript-eslint/no-misused-promises
onSubmit={form.handleSubmit(onSubmit)}
- className="flex flex-col gap-4"
+ className="grid grid-cols-1 gap-6 gap-x-12 lg:grid-cols-3"
>
- <div className="grid grid-cols-4 gap-x-12">
- <div className="col-span-3 row-span-1">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <>
- <FormItem>
- <FormLabel>Name</FormLabel>
- <FormControl>
- <AutoComplete
- {...field}
- options={props.existingEvalTemplates.map(
- (template) => ({
- value: template.name,
- label: template.name,
- }),
- )}
- placeholder=""
- onValueChange={(option) => field.onChange(option.value)}
- value={{ value: field.value, label: field.value }}
- disabled={false}
- createLabel="New eval template name:"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- </>
- )}
- />
- </div>
+ {!props.existingEvalTemplate ? (
+ <>
+ <div className="col-span-1 row-span-1 lg:col-span-2">
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <>
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder="Select a template name"
+ />
+ </FormControl>
+ </FormItem>
+ </>
+ )}
+ />
+ </div>
+ <div className="lg:col-span-0 col-span-1 row-span-1"></div>
+ </>
+ ) : undefined}
- <div className="col-span-3 row-span-4">
- <FormField
- control={form.control}
- name="prompt"
- render={({ field }) => (
- <>
- <FormItem>
- <FormLabel>Prompt</FormLabel>
- <FormControl>
- <Textarea
- {...field}
- className="min-h-[150px] flex-1 font-mono text-xs"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- <FormDescription>
- <p className="text-sm text-gray-500">
- You can use{" "}
- <code className="text-xs">{"{{variable}}"}</code> to
- insert variables into your prompt. The following variables
- are available:
- </p>
-
- <div className="flex flex-wrap gap-2">
- {extractedVariables.map((variable) => (
- <Badge key={variable} variant="outline">
- {variable}
- </Badge>
- ))}
- </div>
- </FormDescription>
- </>
- )}
- />
-
- <FormField
- control={form.control}
- name="outputScore"
- render={({ field }) => (
+ <div className="col-span-1 flex flex-col gap-6 lg:col-span-2">
+ <FormField
+ control={form.control}
+ name="prompt"
+ render={({ field }) => (
+ <>
<FormItem>
- <FormLabel>Score</FormLabel>
+ <FormLabel>Prompt</FormLabel>
<FormControl>
- <Input {...field} />
+ <Textarea
+ {...field}
+ placeholder="{{input}} Please evaluate the input on toxicity."
+ className="min-h-[150px] flex-1 font-mono text-xs"
+ />
</FormControl>
- <FormDescription>Description</FormDescription>
<FormMessage />
+ <PromptDescription
+ currentExtractedVariables={extractedVariables ?? []}
+ />
</FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="outputReasoning"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Reasoning</FormLabel>
- <FormControl>
- <Input {...field} />
- </FormControl>
- <FormDescription>Description</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
+ </>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="outputScore"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Score</FormLabel>
+ <FormControl>
+ <Input {...field} placeholder="Score between 0 and 1" />
+ </FormControl>
+ <FormDescription>
+ We use function calls to extract data from the LLM. Specify
+ what the LLM should return for the score.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
- <div className="col-span-1 row-span-3">
- <ModelParameters
- {...playgroundContext}
- availableModels={[...evalModels]}
- />
- </div>
+ <FormField
+ control={form.control}
+ name="outputReasoning"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Reasoning</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="One sentence reasoning for the score"
+ {...field}
+ />
+ </FormControl>
+ <FormDescription>
+ We use function calls to extract data from the LLM. Specify
+ what the LLM should return for the reasoning.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ <div className="col-span-1 row-span-3">
+ <ModelParameters
+ {...playgroundContext}
+ availableModels={[...evalModels]}
+ disabled={!props.isEditing}
+ />
</div>
- <Button
- type="submit"
- loading={createEvalTemplateMutation.isLoading}
- className="mt-3"
- >
- Save
- </Button>
+ {props.isEditing && (
+ <Button
+ type="submit"
+ loading={createEvalTemplateMutation.isLoading}
+ className="col-span-1 mt-3 lg:col-span-3"
+ >
+ Save
+ </Button>
+ )}
</form>
{formError ? (
<p className="text-red text-center">
diff --git a/web/src/features/evals/constants.ts b/web/src/features/evals/constants.ts
deleted file mode 100644
index 41ee0f21eb..0000000000
--- a/web/src/features/evals/constants.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { z } from "zod";
-
-export const evalModels = z.union([
- z.literal("gpt-3.5-turbo"),
- z.literal("gpt-4"),
-]);
-
-export const evalModelList = evalModels._def.options.map(
- (option) => option.value,
-);
-
-export const jobTypes = ["evaluations"] as const;
-
-export enum JobTypes {
- Evaluation = "evaluation",
-}
-
-export enum EvalTargetObject {
- Trace = "trace",
-}
-
-export const DEFAULT_TRACE_JOB_DELAY = 10_000;
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index d901d0b152..0f7caae726 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -6,19 +6,17 @@ import {
} from "@/src/server/api/trpc";
import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
import { auditLog } from "@/src/features/audit-logs/auditLog";
-import {
- DEFAULT_TRACE_JOB_DELAY,
- EvalTargetObject,
-} from "@/src/features/evals/constants";
+import { DEFAULT_TRACE_JOB_DELAY, EvalTargetObject } from "@langfuse/shared";
import {
EvalModelNames,
ZodModelConfig,
singleFilter,
variableMapping,
} from "@langfuse/shared";
+import { AlphaNumericDashString } from "@/src/utils/zod";
export const CreateEvalTemplate = z.object({
- name: z.string(),
+ name: AlphaNumericDashString,
projectId: z.string(),
prompt: z.string(),
model: EvalModelNames,
@@ -67,12 +65,100 @@ export const evalRouter = createTRPCRouter({
};
}),
+ allTemplatesForName: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ name: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "evalTemplate:read",
+ });
+
+ const templates = await ctx.prisma.evalTemplate.findMany({
+ where: {
+ projectId: input.projectId,
+ name: input.name,
+ },
+ orderBy: [{ version: "desc" }],
+ });
+
+ return {
+ templates: templates,
+ };
+ }),
+
+ templateNames: protectedProjectProcedure
+ .input(
+ z.object({ projectId: z.string(), page: z.number(), limit: z.number() }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "evalTemplate:read",
+ });
+
+ const templates = await ctx.prisma.$queryRaw<
+ Array<{
+ name: string;
+ version: number;
+ latestCreatedAt: Date;
+ latestId: string;
+ }>
+ >`
+ SELECT
+ name,
+ MAX(version) as version,
+ MAX(created_at) as "latestCreatedAt",
+ (SELECT id FROM "eval_templates" WHERE "project_id" = ${input.projectId} AND name = et.name ORDER BY version DESC LIMIT 1) as "latestId"
+ FROM "eval_templates" as et
+ WHERE "project_id" = ${input.projectId}
+ GROUP BY name
+ ORDER BY name
+ LIMIT ${input.limit}
+ OFFSET ${input.page * input.limit}
+ `;
+ return {
+ templates: templates,
+ totalCount: templates.length,
+ };
+ }),
+
+ templateById: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ id: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "evalTemplate:read",
+ });
+
+ const template = await ctx.prisma.evalTemplate.findUnique({
+ where: {
+ id: input.id,
+ projectId: input.projectId,
+ },
+ });
+
+ return template;
+ }),
allTemplates: protectedProjectProcedure
.input(
z.object({
projectId: z.string(),
- limit: z.number(),
- page: z.number(),
+ id: z.string().optional(),
+ limit: z.number().optional(),
+ page: z.number().optional(),
}),
)
.query(async ({ input, ctx }) => {
@@ -85,14 +171,17 @@ export const evalRouter = createTRPCRouter({
const templates = await ctx.prisma.evalTemplate.findMany({
where: {
projectId: input.projectId,
+ ...(input.id ? { id: input.id } : undefined),
},
- take: input.limit,
- skip: input.page * input.limit,
+ ...(input.limit && input.page
+ ? { take: input.limit, skip: input.page * input.limit }
+ : undefined),
});
const count = await ctx.prisma.evalTemplate.count({
where: {
projectId: input.projectId,
+ ...(input.id ? { id: input.id } : undefined),
},
});
return {
@@ -106,7 +195,7 @@ export const evalRouter = createTRPCRouter({
z.object({
projectId: z.string(),
evalTemplateId: z.string(),
- scoreName: z.string(),
+ scoreName: AlphaNumericDashString,
target: z.string(),
filter: z.array(singleFilter).nullable(), // re-using the filter type from the tables
mapping: z.array(variableMapping),
@@ -196,5 +285,6 @@ export const evalRouter = createTRPCRouter({
resourceId: evalTemplate.id,
action: "create",
});
+ return evalTemplate;
}),
});
diff --git a/web/src/features/playground/client/components/ModelParameters.tsx b/web/src/features/playground/client/components/ModelParameters.tsx
index 95b147820a..246bc32556 100644
--- a/web/src/features/playground/client/components/ModelParameters.tsx
+++ b/web/src/features/playground/client/components/ModelParameters.tsx
@@ -16,16 +16,19 @@ import { Slider } from "@/src/components/ui/slider";
export type ModelParamsContext = {
modelParams: UIModelParams;
availableModels?: UIModelParams[];
- updateModelParams: <Key extends keyof UIModelParams>(
+ updateModelParam: <Key extends keyof UIModelParams>(
key: Key,
value: UIModelParams[Key],
) => void;
+ updateModelParams: <UIModelParams>(params: UIModelParams) => void;
+ disabled?: boolean;
};
export const ModelParameters: React.FC<ModelParamsContext> = ({
modelParams,
availableModels,
- updateModelParams,
+ updateModelParam,
+ disabled,
}) => {
return (
<div className="flex flex-col space-y-4">
@@ -34,17 +37,19 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
<ModelParamsSelect
title="Provider"
modelParamsKey="provider"
+ disabled={disabled}
value={modelParams.provider}
options={
availableModels
? [...new Set(availableModels.map((m) => m.provider))]
: Object.values(ModelProvider)
}
- updateModelParams={updateModelParams}
+ updateModelParam={updateModelParam}
/>
<ModelParamsSelect
title="Model name"
modelParamsKey="model"
+ disabled={disabled}
value={modelParams.model}
options={Object.values(
availableModels
@@ -53,37 +58,40 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
.map((m) => m.model)
: supportedModels[modelParams.provider],
)}
- updateModelParams={updateModelParams}
+ updateModelParam={updateModelParam}
/>
<ModelParamsSlider
title="Temperature"
modelParamsKey="temperature"
+ disabled={disabled}
value={modelParams.temperature}
min={0}
max={modelParams.maxTemperature}
step={0.01}
tooltip="The sampling temperature. Higher values will make the output more random, while lower values like will make it more focused and deterministic."
- updateModelParams={updateModelParams}
+ updateModelParam={updateModelParam}
/>
<ModelParamsSlider
title="Output token limit"
modelParamsKey="max_tokens"
+ disabled={disabled}
value={modelParams.max_tokens}
min={1}
max={4096}
step={1}
tooltip="The maximum number of tokens that can be generated in the chat completion."
- updateModelParams={updateModelParams}
+ updateModelParam={updateModelParam}
/>
<ModelParamsSlider
title="Top P"
modelParamsKey="top_p"
+ disabled={disabled}
value={modelParams.top_p}
min={0}
max={1}
step={0.01}
tooltip="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both."
- updateModelParams={updateModelParams}
+ updateModelParam={updateModelParam}
/>
</div>
</div>
@@ -95,21 +103,24 @@ type ModelParamsSelectProps = {
modelParamsKey: keyof UIModelParams;
value: string;
options: string[];
- updateModelParams: ModelParamsContext["updateModelParams"];
+ updateModelParam: ModelParamsContext["updateModelParam"];
+ disabled?: boolean;
};
const ModelParamsSelect = ({
title,
modelParamsKey,
value,
options,
- updateModelParams,
+ updateModelParam,
+ disabled,
}: ModelParamsSelectProps) => {
return (
<div className="space-y-2">
<p className="text-xs font-semibold">{title}</p>
<Select
+ disabled={disabled}
onValueChange={(value) =>
- updateModelParams(
+ updateModelParam(
modelParamsKey,
value as (typeof supportedModels)[ModelProvider][number],
)
@@ -139,7 +150,8 @@ type ModelParamsSliderProps = {
min: number;
max: number;
step: number;
- updateModelParams: ModelParamsContext["updateModelParams"];
+ updateModelParam: ModelParamsContext["updateModelParam"];
+ disabled?: boolean;
};
const ModelParamsSlider = ({
title,
@@ -149,7 +161,8 @@ const ModelParamsSlider = ({
min,
max,
step,
- updateModelParams,
+ updateModelParam,
+ disabled,
}: ModelParamsSliderProps) => {
return (
<div className="space-y-3" title={tooltip}>
@@ -158,12 +171,13 @@ const ModelParamsSlider = ({
<Input
className="h-6 w-14 appearance-none px-2 text-right"
type="number"
+ disabled={disabled}
min={min}
max={max}
step={step}
value={value}
onChange={(event) => {
- updateModelParams(
+ updateModelParam(
modelParamsKey,
Math.max(Math.min(parseFloat(event.target.value), max), min),
);
@@ -171,12 +185,13 @@ const ModelParamsSlider = ({
/>
</div>
<Slider
+ disabled={disabled}
min={min}
max={max}
step={step}
onValueChange={(value) => {
if (value[0] !== undefined)
- updateModelParams(modelParamsKey, value[0]);
+ updateModelParam(modelParamsKey, value[0]);
}}
value={[value]}
/>
diff --git a/web/src/features/playground/client/context/index.tsx b/web/src/features/playground/client/context/index.tsx
index 338f83a853..8f01a5674c 100644
--- a/web/src/features/playground/client/context/index.tsx
+++ b/web/src/features/playground/client/context/index.tsx
@@ -205,13 +205,19 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({
useCommandEnter(!isStreaming, handleSubmit);
- const updateModelParams: PlaygroundContextType["updateModelParams"] = (
+ const updateModelParam: PlaygroundContextType["updateModelParam"] = (
key,
value,
) => {
setModelParams((prev) => ({ ...prev, [key]: value }));
};
+ const updateModelParams: PlaygroundContextType["updateModelParams"] = (
+ params,
+ ) => {
+ setModelParams((prev) => ({ ...prev, ...params }));
+ };
+
const updatePromptVariableValue = (variable: string, value: string) => {
setPromptVariables((prev) =>
prev.map((v) => (v.name === variable ? { ...v, value } : v)),
@@ -235,7 +241,8 @@ export const PlaygroundProvider: React.FC<PlaygroundProviderProps> = ({
deleteMessage,
modelParams,
- updateModelParams,
+ updateModelParam: updateModelParam,
+ updateModelParams: updateModelParams,
output,
outputJson,
diff --git a/web/src/features/prompts/components/NewPromptForm/index.tsx b/web/src/features/prompts/components/NewPromptForm/index.tsx
index ee26c5ff4c..ae9db4656b 100644
--- a/web/src/features/prompts/components/NewPromptForm/index.tsx
+++ b/web/src/features/prompts/components/NewPromptForm/index.tsx
@@ -3,7 +3,6 @@ import router from "next/router";
import { usePostHog } from "posthog-js/react";
import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
-import { Badge } from "@/src/components/ui/badge";
import { Button } from "@/src/components/ui/button";
import { Checkbox } from "@/src/components/ui/checkbox";
import {
@@ -41,6 +40,7 @@ import {
import { Input } from "@/src/components/ui/input";
import Link from "next/link";
import { ArrowTopRightIcon } from "@radix-ui/react-icons";
+import { PromptDescription } from "@/src/features/prompts/components/prompt-description";
import { JsonEditor } from "@/src/components/json-editor";
type NewPromptFormProps = {
@@ -269,24 +269,9 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
</TabsContent>
</Tabs>
</FormItem>
- <p className="text-sm text-gray-500">
- You can use <code className="text-xs">{"{{variable}}"}</code> to
- insert variables into your prompt.
- <b className="font-semibold"> Note:</b> Variables must be
- alphabetical characters or underscores.
- {currentExtractedVariables.length > 0
- ? " The following variables are available:"
- : ""}
- </p>
- {currentExtractedVariables.length > 0 && (
- <div className="flex min-h-6 flex-wrap gap-2">
- {currentExtractedVariables.map((variable) => (
- <Badge key={variable} variant="outline">
- {variable}
- </Badge>
- ))}
- </div>
- )}
+ <PromptDescription
+ currentExtractedVariables={currentExtractedVariables}
+ />
</>
{/* Prompt Config field */}
diff --git a/web/src/features/prompts/components/prompt-description.tsx b/web/src/features/prompts/components/prompt-description.tsx
new file mode 100644
index 0000000000..3c31d9c8a2
--- /dev/null
+++ b/web/src/features/prompts/components/prompt-description.tsx
@@ -0,0 +1,28 @@
+import { Badge } from "@/src/components/ui/badge";
+
+export const PromptDescription = ({
+ currentExtractedVariables,
+}: {
+ currentExtractedVariables: string[];
+}) => {
+ return (
+ <>
+ <p className="text-sm text-gray-500">
+ You can use <code className="text-xs">{"{{variable}}"}</code> to insert
+ variables into your prompt.
+ <b className="font-semibold"> Note:</b> Variables must be alphabetical
+ characters or underscores.
+ {currentExtractedVariables.length > 0
+ ? " The following variables are available:"
+ : ""}
+ </p>
+ <div className="flex min-h-6 flex-wrap gap-2">
+ {currentExtractedVariables.map((variable) => (
+ <Badge key={variable} variant="outline">
+ {variable}
+ </Badge>
+ ))}
+ </div>
+ </>
+ );
+};
diff --git a/web/src/pages/project/[projectId]/evals/configs/index.tsx b/web/src/pages/project/[projectId]/evals/configs/index.tsx
index 9fd1c50d14..11b8f5ac47 100644
--- a/web/src/pages/project/[projectId]/evals/configs/index.tsx
+++ b/web/src/pages/project/[projectId]/evals/configs/index.tsx
@@ -11,7 +11,7 @@ import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { Lock } from "lucide-react";
import EvalConfigTable from "@/src/features/evals/components/eval-config-table";
-export default function TemplatesPage() {
+export default function ConfigsPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
diff --git a/web/src/pages/project/[projectId]/evals/configs/new.tsx b/web/src/pages/project/[projectId]/evals/configs/new.tsx
index d537df8bbe..6df1b1370f 100644
--- a/web/src/pages/project/[projectId]/evals/configs/new.tsx
+++ b/web/src/pages/project/[projectId]/evals/configs/new.tsx
@@ -4,7 +4,7 @@ import { api } from "@/src/utils/api";
import { useRouter } from "next/router";
-export default function TemplatesPage() {
+export default function NewConfigsPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
diff --git a/web/src/pages/project/[projectId]/evals/templates/[id].tsx b/web/src/pages/project/[projectId]/evals/templates/[id].tsx
new file mode 100644
index 0000000000..ecc37178ee
--- /dev/null
+++ b/web/src/pages/project/[projectId]/evals/templates/[id].tsx
@@ -0,0 +1,3 @@
+import { EvalTemplateDetail } from "@/src/features/evals/components/eval-template-detail";
+
+export default EvalTemplateDetail;
diff --git a/web/src/pages/project/[projectId]/evals/templates/new.tsx b/web/src/pages/project/[projectId]/evals/templates/new.tsx
index 41acb067ec..bbed868e7a 100644
--- a/web/src/pages/project/[projectId]/evals/templates/new.tsx
+++ b/web/src/pages/project/[projectId]/evals/templates/new.tsx
@@ -1,23 +1,17 @@
import Header from "@/src/components/layouts/header";
-import { NewEvalTemplateForm } from "@/src/features/evals/components/new-template-form";
+import { EvalTemplateForm } from "@/src/features/evals/components/new-template-form";
import { PlaygroundProvider } from "@/src/features/playground/client/context";
import { api } from "@/src/utils/api";
import { evalModels } from "@langfuse/shared";
import { useRouter } from "next/router";
-export default function TemplatesPage() {
+export default function NewTemplatesPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
- const evals = api.evals.allTemplates.useQuery({
- projectId: projectId,
- limit: 500,
- page: 0,
- });
-
return (
- <div>
+ <div className="md:container">
<Header
title="Create eval template"
help={{
@@ -27,10 +21,7 @@ export default function TemplatesPage() {
}}
/>
<PlaygroundProvider avilableModels={[...evalModels]}>
- <NewEvalTemplateForm
- projectId={projectId}
- existingEvalTemplates={evals.data?.templates ?? []}
- />
+ <EvalTemplateForm projectId={projectId} isEditing={true} />
</PlaygroundProvider>
</div>
);
diff --git a/web/src/utils/zod.ts b/web/src/utils/zod.ts
index eae55d84ff..6bfd925c93 100644
--- a/web/src/utils/zod.ts
+++ b/web/src/utils/zod.ts
@@ -53,3 +53,8 @@ export const noHtmlRegex = /<[^>]*>/;
export const noHtmlCheck = (value: string) => !noHtmlRegex.test(value);
export const NonEmptyString = z.string().min(1);
+
+export const AlphaNumericDashString = z
+ .string()
+ .min(1, "Enter a name")
+ .regex(/^[A-Za-z0-9-]+$/, "Must be alphanumeric or contain dashes (-)");