Skip to content

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

feat(ui): custom model prices and tokenization (#954)

Marc Klingenf3fd52fdbbe9
diff --git a/src/components/date-picker.tsx b/src/components/date-picker.tsx
index ddc4068019..e33894c3c9 100644
--- a/src/components/date-picker.tsx
+++ b/src/components/date-picker.tsx
@@ -1,7 +1,7 @@
"use client";
import * as React from "react";
-import { Calendar as CalendarIcon } from "lucide-react";
+import { Calendar as CalendarIcon, X } from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { Calendar } from "@/src/components/ui/calendar";
import {
@@ -39,36 +39,50 @@ export type AvailableDateRangeSelections =
export function DatePicker({
date,
onChange,
+ clearable = false,
className,
}: {
date?: Date | undefined;
onChange: (date: Date | undefined) => void;
+ clearable?: boolean;
className?: string;
}) {
return (
- <Popover>
- <PopoverTrigger asChild>
+ <div className="flex flex-row gap-2 align-middle">
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant={"outline"}
+ className={cn(
+ "justify-start text-left font-normal",
+ !date && "text-muted-foreground",
+ className,
+ )}
+ >
+ <CalendarIcon className="mr-2 h-4 w-4" />
+ {date ? format(date, "PPP") : <span>Pick a date</span>}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-0">
+ <Calendar
+ mode="single"
+ selected={date}
+ onSelect={(d) => onChange(d)}
+ initialFocus
+ />
+ </PopoverContent>
+ </Popover>
+ {date && clearable && (
<Button
- variant={"outline"}
- className={cn(
- "justify-start text-left font-normal",
- !date && "text-muted-foreground",
- className,
- )}
+ variant="ghost"
+ size="icon"
+ onClick={() => onChange(undefined)}
+ title="reset date"
>
- <CalendarIcon className="mr-2 h-4 w-4" />
- {date ? format(date, "PPP") : <span>Pick a date</span>}
+ <X size={14} />
</Button>
- </PopoverTrigger>
- <PopoverContent className="w-auto p-0">
- <Calendar
- mode="single"
- selected={date}
- onSelect={(d) => onChange(d)}
- initialFocus
- />
- </PopoverContent>
- </Popover>
+ )}
+ </div>
);
}
diff --git a/src/components/layouts/doc-popup.tsx b/src/components/layouts/doc-popup.tsx
index 179e683c49..2e4e0accdb 100644
--- a/src/components/layouts/doc-popup.tsx
+++ b/src/components/layouts/doc-popup.tsx
@@ -3,22 +3,25 @@ import {
HoverCardContent,
HoverCardTrigger,
} from "@/src/components/ui/hover-card";
-import { HelpCircle } from "lucide-react";
+import { HelpCircle, Info } from "lucide-react";
import Link from "next/link";
import { usePostHog } from "posthog-js/react";
export type DocPopupProps = {
description: React.ReactNode;
- href: string;
- size?: "sm" | "md" | "lg";
+ href?: string;
+ style?: "question" | "info";
+ size?: "xs" | "sm" | "md" | "lg";
};
export default function DocPopup({
description,
href,
+ style = "info",
size = "sm",
}: DocPopupProps) {
const sizes = {
+ xs: "w-3 h-3",
sm: "w-4 h-4",
md: "w-6 h-6",
lg: "w-8 h-8",
@@ -35,14 +38,30 @@ export default function DocPopup({
}}
>
<HoverCardTrigger className="mx-1 cursor-pointer" asChild>
- <Link
- href={href}
- rel="noopener"
- target="_blank"
- className="inline-block whitespace-nowrap text-gray-500 sm:pl-0"
- >
- <HelpCircle className={sizes[size]} />
- </Link>
+ {href ? (
+ <Link
+ href={href}
+ rel="noopener"
+ target="_blank"
+ className="inline-block whitespace-nowrap text-gray-500 sm:pl-0"
+ >
+ {
+ {
+ question: <HelpCircle className={sizes[size]} />,
+ info: <Info className={sizes[size]} />,
+ }[style]
+ }
+ </Link>
+ ) : (
+ <div className="inline-block whitespace-nowrap text-gray-500 sm:pl-0">
+ {
+ {
+ question: <HelpCircle className={sizes[size]} />,
+ info: <Info className={sizes[size]} />,
+ }[style]
+ }
+ </div>
+ )}
</HoverCardTrigger>
<HoverCardContent>
{typeof description === "string" ? (
diff --git a/src/components/layouts/header.tsx b/src/components/layouts/header.tsx
index 0fe06a8a55..e005252366 100644
--- a/src/components/layouts/header.tsx
+++ b/src/components/layouts/header.tsx
@@ -13,7 +13,7 @@ export default function Header({
title: string;
breadcrumb?: { name: string; href?: string }[];
status?: Status;
- help?: { description: string; href: string };
+ help?: { description: string; href?: string };
actionButtons?: React.ReactNode;
level?: "h2" | "h3";
}) {
diff --git a/src/components/table/data-table.tsx b/src/components/table/data-table.tsx
index 6016deaf81..294658bd0b 100644
--- a/src/components/table/data-table.tsx
+++ b/src/components/table/data-table.tsx
@@ -3,6 +3,7 @@
import DocPopup from "@/src/components/layouts/doc-popup";
import { DataTablePagination } from "@/src/components/table/data-table-pagination";
import { type LangfuseColumnDef } from "@/src/components/table/types";
+import { type ModelTableRow } from "@/src/components/table/use-cases/models";
import {
Table,
TableBody,
@@ -100,8 +101,9 @@ export function DataTable<TData extends object, TValue>({
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
- const sortingEnabled =
- header.column.columnDef.enableSorting;
+ const columnDef = header.column
+ .columnDef as LangfuseColumnDef<ModelTableRow>;
+ const sortingEnabled = columnDef.enableSorting;
return header.column.getIsVisible() ? (
<TableHead
key={header.id}
@@ -113,18 +115,14 @@ export function DataTable<TData extends object, TValue>({
onClick={(event) => {
event.preventDefault(); // Add this line
- if (
- !setOrderBy ||
- !header.column.columnDef.id ||
- !sortingEnabled
- ) {
+ if (!setOrderBy || !columnDef.id || !sortingEnabled) {
return;
}
- if (orderBy?.column === header.column.columnDef.id) {
+ if (orderBy?.column === columnDef.id) {
if (orderBy.order === "DESC") {
setOrderBy({
- column: header.column.columnDef.id,
+ column: columnDef.id,
order: "ASC",
});
} else {
@@ -132,7 +130,7 @@ export function DataTable<TData extends object, TValue>({
}
} else {
setOrderBy({
- column: header.column.columnDef.id,
+ column: columnDef.id,
order: "DESC",
});
}
@@ -146,7 +144,17 @@ export function DataTable<TData extends object, TValue>({
header.getContext(),
)}
- {orderBy?.column === header.column.columnDef.id
+ {columnDef.headerTooltip && (
+ <DocPopup
+ description={
+ columnDef.headerTooltip.description
+ }
+ href={columnDef.headerTooltip.href}
+ size="xs"
+ />
+ )}
+
+ {orderBy?.column === columnDef.id
? renderOrderingIndicator(orderBy)
: null}
</div>
diff --git a/src/components/table/types.ts b/src/components/table/types.ts
index 029273a949..002eafb563 100644
--- a/src/components/table/types.ts
+++ b/src/components/table/types.ts
@@ -9,4 +9,10 @@ export type TableRowOptions = {
export type LangfuseColumnDef<
TData extends RowData,
TValue = unknown,
-> = ColumnDef<TData, TValue> & { defaultHidden?: boolean };
+> = ColumnDef<TData, TValue> & {
+ defaultHidden?: boolean;
+ headerTooltip?: {
+ description: string;
+ href?: string;
+ };
+};
diff --git a/src/components/table/use-cases/models.tsx b/src/components/table/use-cases/models.tsx
index 87ca2d9a32..3302e8cce3 100644
--- a/src/components/table/use-cases/models.tsx
+++ b/src/components/table/use-cases/models.tsx
@@ -1,13 +1,17 @@
import { DataTable } from "@/src/components/table/data-table";
import { type LangfuseColumnDef } from "@/src/components/table/types";
+import { Button } from "@/src/components/ui/button";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { api } from "@/src/utils/api";
import { usdFormatter } from "@/src/utils/numbers";
import { type Prisma, type Model } from "@prisma/client";
import Decimal from "decimal.js";
+import { Trash } from "lucide-react";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
export type ModelTableRow = {
+ modelId: string;
maintainer: string;
modelName: string;
matchPattern: string;
@@ -20,6 +24,24 @@ export type ModelTableRow = {
config?: Prisma.JsonValue;
};
+const modelConfigDescriptions = {
+ modelName:
+ "Standardized model name. Generations are assigned to this model name if they match the `matchPattern` upon ingestion.",
+ matchPattern:
+ "Regex pattern to match `model` parameter of generations to model pricing",
+ startDate:
+ "Date to start pricing model. If not set, model is active unless a more recent version exists.",
+ inputPrice: "Price per unit of input",
+ outputPrice: "Price per unit of output",
+ totalPrice:
+ "Price per unit, for models that don't have input/output specific prices",
+ unit: "Unit of measurement for model, can be TOKENS or CHARACTERS.",
+ tokenizerId:
+ "Tokenizer used for this model to calculate token counts if none are ingested. Pick from list of supported tokenizers.",
+ config:
+ "Some tokenizers require additional configuration (e.g. openai tiktoken). See docs for details.",
+} as const;
+
export default function ModelTable({ projectId }: { projectId: string }) {
const [paginationState, setPaginationState] = useQueryParams({
pageIndex: withDefault(NumberParam, 0),
@@ -44,39 +66,51 @@ export default function ModelTable({ projectId }: { projectId: string }) {
accessorKey: "modelName",
id: "modelName",
header: "Model Name",
- },
- {
- accessorKey: "matchPattern",
- id: "matchPattern",
- header: "Match Pattern",
- cell: ({ row }) => {
- const value: string = row.getValue("matchPattern");
-
- return (
- <code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs ">
- {value}
- </code>
- );
+ headerTooltip: {
+ description: modelConfigDescriptions.modelName,
},
},
{
accessorKey: "startDate",
id: "startDate",
header: "Start Date",
+ headerTooltip: {
+ description: modelConfigDescriptions.startDate,
+ },
cell: ({ row }) => {
const value: Date | undefined = row.getValue("startDate");
return value ? (
- <span className="text-xs">{value.toLocaleDateString()} </span>
+ <span className="text-xs">{value.toISOString().slice(0, 10)} </span>
) : (
<span className="text-xs">-</span>
);
},
},
+ {
+ accessorKey: "matchPattern",
+ id: "matchPattern",
+ headerTooltip: {
+ description: modelConfigDescriptions.matchPattern,
+ },
+ header: "Match Pattern",
+ cell: ({ row }) => {
+ const value: string = row.getValue("matchPattern");
+
+ return (
+ <code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs ">
+ {value}
+ </code>
+ );
+ },
+ },
{
accessorKey: "inputPrice",
id: "inputPrice",
header: "Input Price",
+ headerTooltip: {
+ description: modelConfigDescriptions.inputPrice,
+ },
cell: ({ row }) => {
const value: Decimal | undefined = row.getValue("inputPrice");
@@ -92,6 +126,9 @@ export default function ModelTable({ projectId }: { projectId: string }) {
{
accessorKey: "outputPrice",
id: "outputPrice",
+ headerTooltip: {
+ description: modelConfigDescriptions.outputPrice,
+ },
header: "Output Price",
cell: ({ row }) => {
const value: Decimal | undefined = row.getValue("outputPrice");
@@ -109,6 +146,9 @@ export default function ModelTable({ projectId }: { projectId: string }) {
accessorKey: "totalPrice",
id: "totalPrice",
header: "Total Price",
+ headerTooltip: {
+ description: modelConfigDescriptions.totalPrice,
+ },
cell: ({ row }) => {
const value: Decimal | undefined = row.getValue("totalPrice");
@@ -125,18 +165,27 @@ export default function ModelTable({ projectId }: { projectId: string }) {
accessorKey: "unit",
id: "unit",
header: "Unit",
+ headerTooltip: {
+ description: modelConfigDescriptions.unit,
+ },
enableHiding: true,
},
{
accessorKey: "tokenizerId",
id: "tokenizerId",
header: "Tokenizer",
+ headerTooltip: {
+ description: modelConfigDescriptions.tokenizerId,
+ },
enableHiding: true,
},
{
accessorKey: "config",
id: "config",
- header: "Tokenizer",
+ header: "Tokenizer Configuration",
+ headerTooltip: {
+ description: modelConfigDescriptions.config,
+ },
enableHiding: true,
cell: ({ row }) => {
const value: Prisma.JsonValue | undefined = row.getValue("config");
@@ -148,6 +197,20 @@ export default function ModelTable({ projectId }: { projectId: string }) {
);
},
},
+ {
+ accessorKey: "actions",
+ header: "Actions",
+ cell: ({ row }) => {
+ return row.original.maintainer === "User" ? (
+ <DeleteModelButton
+ projectId={projectId}
+ modelId={row.original.modelId}
+ />
+ ) : (
+ <div className="h-6" />
+ );
+ },
+ },
];
const [columnVisibility, setColumnVisibility] =
@@ -155,6 +218,7 @@ export default function ModelTable({ projectId }: { projectId: string }) {
const convertToTableRow = (model: Model): ModelTableRow => {
return {
+ modelId: model.id,
maintainer: model.projectId ? "User" : "Langfuse",
modelName: model.modelName,
matchPattern: model.matchPattern,
@@ -200,3 +264,46 @@ export default function ModelTable({ projectId }: { projectId: string }) {
</div>
);
}
+
+const DeleteModelButton = ({
+ modelId,
+ projectId,
+}: {
+ modelId: string;
+ projectId: string;
+}) => {
+ const utils = api.useUtils();
+ const mut = api.models.delete.useMutation({
+ onSuccess: () => {
+ void utils.models.invalidate();
+ },
+ });
+
+ const hasAccess = useHasAccess({
+ projectId,
+ scope: "models:CUD",
+ });
+
+ if (!hasAccess) {
+ return null;
+ }
+
+ return (
+ <Button
+ size="xs"
+ variant="ghost"
+ onClick={() => {
+ mut
+ .mutateAsync({
+ projectId,
+ modelId,
+ })
+ .catch((error) => {
+ console.error(error);
+ });
+ }}
+ >
+ <Trash size={14} />
+ </Button>
+ );
+};
diff --git a/src/features/models/components/NewModelForm.tsx b/src/features/models/components/NewModelForm.tsx
new file mode 100644
index 0000000000..c200743840
--- /dev/null
+++ b/src/features/models/components/NewModelForm.tsx
@@ -0,0 +1,376 @@
+import { Button } from "@/src/components/ui/button";
+import * as z from "zod";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useForm } from "react-hook-form";
+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 { api } from "@/src/utils/api";
+import { useState } from "react";
+import { usePostHog } from "posthog-js/react";
+import { Input } from "@/src/components/ui/input";
+import { DatePicker } from "@/src/components/date-picker";
+import Header from "@/src/components/layouts/header";
+import { AutoComplete } from "@/src/features/prompts/components/auto-complete";
+import JsonView from "react18-json-view";
+
+const formSchema = z.object({
+ modelName: z.string().min(1),
+ exactMatchPattern: z
+ .string()
+ .regex(
+ /^[a-zA-Z0-9_.-]+$/,
+ "Match pattern must be alphanumeric and may contain _.-",
+ ), // risk of invalid regex injection that would break the db join,
+ startDate: z.date().optional(),
+ inputPrice: z
+ .string()
+ .refine((value) => value === "" || isFinite(parseFloat(value)), {
+ message: "Price needs to be numeric",
+ })
+ .optional(),
+ outputPrice: z
+ .string()
+ .refine((value) => value === "" || isFinite(parseFloat(value)), {
+ message: "Price needs to be numeric",
+ })
+ .optional(),
+ totalPrice: z
+ .string()
+ .refine((value) => value === "" || isFinite(parseFloat(value)), {
+ message: "Price needs to be numeric",
+ })
+ .optional(),
+ unit: z.enum(["TOKENS", "CHARACTERS"]),
+ tokenizerId: z.enum(["openai", "claude", "None"]),
+ tokenizerConfig: z.string().refine(
+ (value) => {
+ try {
+ JSON.parse(value);
+ return true;
+ } catch (e) {
+ return false;
+ }
+ },
+ {
+ message: "Tokenizer config needs to be valid JSON",
+ },
+ ),
+});
+
+export const NewModelForm = (props: {
+ projectId: string;
+ onFormSuccess?: () => void;
+}) => {
+ const [formError, setFormError] = useState<string | null>(null);
+ const posthog = usePostHog();
+ const form = useForm<z.infer<typeof formSchema>>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ modelName: "",
+ exactMatchPattern: "",
+ startDate: undefined,
+ inputPrice: "",
+ outputPrice: "",
+ totalPrice: "",
+ unit: "TOKENS",
+ tokenizerId: "None",
+ tokenizerConfig: "{}",
+ },
+ });
+
+ const utils = api.useUtils();
+ const createModelMutation = api.models.create.useMutation({
+ onSuccess: () => utils.models.invalidate(),
+ onError: (error) => setFormError(error.message),
+ });
+
+ const modelNames = api.models.modelNames.useQuery({
+ projectId: props.projectId,
+ });
+
+ function onSubmit(values: z.infer<typeof formSchema>) {
+ posthog.capture("models:new_model_form_submit");
+ createModelMutation
+ .mutateAsync({
+ projectId: props.projectId,
+ modelName: values.modelName,
+ exactMatchPattern: values.exactMatchPattern,
+ inputPrice: !!values.inputPrice
+ ? parseFloat(values.inputPrice)
+ : undefined,
+ outputPrice: !!values.outputPrice
+ ? parseFloat(values.outputPrice)
+ : undefined,
+ totalPrice: !!values.totalPrice
+ ? parseFloat(values.totalPrice)
+ : undefined,
+ unit: values.unit,
+ tokenizerId:
+ values.tokenizerId === "None" ? undefined : values.tokenizerId,
+ tokenizerConfig:
+ values.tokenizerConfig &&
+ typeof JSON.parse(values.tokenizerConfig) === "object"
+ ? (JSON.parse(values.tokenizerConfig) as Record<string, number>)
+ : undefined,
+ })
+ .then(() => {
+ props.onFormSuccess?.();
+ form.reset();
+ })
+ .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"
+ >
+ <Header level="h3" title="Name" />
+ <FormField
+ control={form.control}
+ name="modelName"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Model Name</FormLabel>
+ <FormControl>
+ <AutoComplete
+ {...field}
+ options={
+ modelNames.data?.map((model) => ({
+ value: model,
+ label: model,
+ })) ?? []
+ }
+ placeholder=""
+ onValueChange={(option) => field.onChange(option.value)}
+ value={{ value: field.value, label: field.value }}
+ disabled={false}
+ />
+ </FormControl>
+ <FormDescription>
+ The name of the model. This will be used to reference the model
+ in the API. You can track price changes of models by using the
+ same name and match pattern.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Header level="h3" title="Scope" />
+ <FormField
+ control={form.control}
+ name="exactMatchPattern"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Match pattern</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormDescription>
+ `model` on generations that should match this model,
+ case-insensitive.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="startDate"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Start date</FormLabel>
+ <FormControl>
+ <DatePicker
+ date={field.value}
+ onChange={(date) => field.onChange(date)}
+ clearable
+ />
+ </FormControl>
+ <FormDescription>
+ If set, the model will only be used for generations after this
+ date.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Header level="h3" title="Pricing" />
+ <FormField
+ control={form.control}
+ name="unit"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Unit</FormLabel>
+ <Select onValueChange={field.onChange} defaultValue={field.value}>
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select a unit" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {["TOKENS", "CHARACTERS"].map((unit) => (
+ <SelectItem value={unit} key={unit}>
+ {unit}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormDescription>
+ The unit of measurement for the model.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <div className="grid grid-cols-3 gap-2">
+ <FormField
+ control={form.control}
+ name="inputPrice"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Input price (USD)</FormLabel>
+ <FormControl>
+ <Input {...field} type="number" />
+ </FormControl>
+ <FormDescription>Cost per input unit.</FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="outputPrice"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Output price (USD)</FormLabel>
+ <FormControl>
+ <Input {...field} type="number" />
+ </FormControl>
+ <FormDescription>Cost per output unit.</FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="totalPrice"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Total price (USD)</FormLabel>
+ <FormControl>
+ <Input {...field} type="number" />
+ </FormControl>
+ <FormDescription>
+ Cost per unit, if no separate input/output prices.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ <Header level="h3" title="Tokenization" />
+ <FormField
+ control={form.control}
+ name="tokenizerId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Tokenizer</FormLabel>
+ <Select
+ onValueChange={(tokenizerId) => {
+ field.onChange(tokenizerId);
+ if (tokenizerId === "None") {
+ form.setValue("tokenizerConfig", "{}");
+ }
+ }}
+ defaultValue={field.value}
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select a unit" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {["openai", "claude", "None"].map((unit) => (
+ <SelectItem value={unit} key={unit}>
+ {unit}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormDescription>
+ Optionally, Langfuse can tokenize the input and output of a
+ generation if no unit counts are ingested. This is useful for
+ e.g. streamed OpenAI completions. For details on the supported
+ tokenizers, see the docs.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ {form.watch("tokenizerId") !== "None" && (
+ <FormField
+ control={form.control}
+ name="tokenizerConfig"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Tokenizer Config</FormLabel>
+ <JsonView
+ src={JSON.parse(field.value) as unknown}
+ onEdit={(edit) => {
+ field.onChange(JSON.stringify(edit.src));
+ }}
+ editable
+ className="rounded-md border border-gray-200 p-2 text-sm"
+ />
+ <FormDescription>
+ The config for the tokenizer. Required for openai. See the
+ docs for details.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+ <Button
+ type="submit"
+ loading={createModelMutation.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/src/features/prompts/components/auto-complete.tsx b/src/features/prompts/components/auto-complete.tsx
index 46d8760fd8..5aef944b7b 100644
--- a/src/features/prompts/components/auto-complete.tsx
+++ b/src/features/prompts/components/auto-complete.tsx
@@ -96,7 +96,6 @@ export const AutoComplete = ({
onFocus={() => setOpen(true)}
placeholder={placeholder}
disabled={disabled}
- className="text-base"
/>
</div>
<div className="relative mt-1">
diff --git a/src/features/rbac/constants/roleAccessRights.ts b/src/features/rbac/constants/roleAccessRights.ts
index e801fdc5a8..8ace4b6684 100644
--- a/src/features/rbac/constants/roleAccessRights.ts
+++ b/src/features/rbac/constants/roleAccessRights.ts
@@ -25,6 +25,8 @@ const scopes = [
"prompts:CUD",
"prompts:read",
+
+ "models:CUD",
] as const;
// type string of all Resource:Action, e.g. "members:read"
@@ -49,6 +51,7 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"datasets:CUD",
"prompts:CUD",
"prompts:read",
+ "models:CUD",
],
ADMIN: [
"project:update",
@@ -66,6 +69,7 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"datasets:CUD",
"prompts:CUD",
"prompts:read",
+ "models:CUD",
],
MEMBER: [
"members:read",
diff --git a/src/pages/project/[projectId]/models.tsx b/src/pages/project/[projectId]/models.tsx
index 8100902ea6..ed96d54a3b 100644
--- a/src/pages/project/[projectId]/models.tsx
+++ b/src/pages/project/[projectId]/models.tsx
@@ -2,10 +2,15 @@ import Header from "@/src/components/layouts/header";
import { useRouter } from "next/router";
import ModelTable from "@/src/components/table/use-cases/models";
+import { Button } from "@/src/components/ui/button";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { Lock } from "lucide-react";
+import Link from "next/link";
export default function ModelsPage() {
const router = useRouter();
const projectId = router.query.projectId as string;
+ const hasWriteAccess = useHasAccess({ projectId, scope: "models:CUD" });
return (
<div>
@@ -16,6 +21,14 @@ export default function ModelsPage() {
"A model represents a LLM model. It is used to calculate tokens and cost.",
href: "https://langfuse.com/docs/token-usage",
}}
+ actionButtons={
+ <Button disabled={!hasWriteAccess} asChild>
+ <Link href={`/project/${projectId}/models/new`}>
+ {!hasWriteAccess && <Lock size={16} className="mr-2" />}
+ Add model definition{" "}
+ </Link>
+ </Button>
+ }
/>
<ModelTable projectId={projectId} />
</div>
diff --git a/src/pages/project/[projectId]/models/new.tsx b/src/pages/project/[projectId]/models/new.tsx
new file mode 100644
index 0000000000..06004df57e
--- /dev/null
+++ b/src/pages/project/[projectId]/models/new.tsx
@@ -0,0 +1,30 @@
+import Header from "@/src/components/layouts/header";
+
+import { useRouter } from "next/router";
+import { NewModelForm } from "@/src/features/models/components/NewModelForm";
+
+export default function ModelsPage() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+
+ return (
+ <div className="mb-12 md:container">
+ <Header
+ title="New Model"
+ breadcrumb={[
+ {
+ name: "Models",
+ href: `/project/${projectId}/models`,
+ },
+ {
+ name: "New",
+ },
+ ]}
+ />
+ <NewModelForm
+ projectId={projectId}
+ onFormSuccess={() => void router.push(`/project/${projectId}/models`)}
+ />
+ </div>
+ );
+}
diff --git a/src/server/api/routers/models.ts b/src/server/api/routers/models.ts
index f16d18765d..4ab9de3721 100644
--- a/src/server/api/routers/models.ts
+++ b/src/server/api/routers/models.ts
@@ -5,6 +5,7 @@ import {
protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { paginationZod } from "@/src/utils/zod";
+import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
const ModelAllOptions = z.object({
projectId: z.string(),
@@ -20,7 +21,16 @@ export const modelRouter = createTRPCRouter({
OR: [{ projectId: input.projectId }, { projectId: null }],
},
skip: input.page * input.limit,
- orderBy: [{ modelName: "asc" }, { startDate: "desc" }],
+ orderBy: [
+ { modelName: "asc" },
+ { unit: "asc" },
+ {
+ startDate: {
+ sort: "desc",
+ nulls: "last",
+ },
+ },
+ ],
take: input.limit,
});
@@ -30,9 +40,100 @@ export const modelRouter = createTRPCRouter({
},
});
+ console.log("models", models);
+
return {
models,
totalCount: totalAmount,
};
}),
+ modelNames: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ return (
+ await ctx.prisma.model.findMany({
+ select: {
+ modelName: true,
+ },
+ distinct: ["modelName"],
+ orderBy: [{ modelName: "asc" }],
+ where: {
+ OR: [{ projectId: input.projectId }, { projectId: null }],
+ },
+ })
+ ).map((model) => model.modelName);
+ }),
+ delete: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ modelId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "models:CUD",
+ });
+
+ return ctx.prisma.model.delete({
+ where: {
+ id: input.modelId,
+ projectId: input.projectId,
+ },
+ });
+ }),
+ create: protectedProjectProcedure
+ .input(
+ z
+ .object({
+ projectId: z.string(),
+ modelName: z.string(),
+ exactMatchPattern: z
+ .string()
+ .regex(
+ /^[a-zA-Z0-9_.-]+$/,
+ "Match pattern must be alphanumeric and may contain _.-",
+ ), // risk of invalid regex injection that would break the db join
+ startDate: z.date().optional(),
+ inputPrice: z.number().positive().optional(),
+ outputPrice: z.number().positive().optional(),
+ totalPrice: z.number().positive().optional(),
+ unit: z.enum(["TOKENS", "CHARACTERS"]),
+ tokenizerId: z.enum(["openai", "claude"]).optional(),
+ tokenizerConfig: z
+ .record(z.union([z.string(), z.number()]))
+ .optional(),
+ })
+ .refine(
+ ({ inputPrice, outputPrice, totalPrice }) =>
+ (!!inputPrice && !!outputPrice) || !!totalPrice,
+ {
+ message:
+ "Either inputPrice and outputPrice or totalPrice needs to be set",
+ },
+ ),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "models:CUD",
+ });
+ return ctx.prisma.model.create({
+ data: {
+ projectId: input.projectId,
+ modelName: input.modelName,
+ matchPattern: `(?i)^(${input.exactMatchPattern})$`,
+ startDate: input.startDate,
+ inputPrice: input.inputPrice,
+ outputPrice: input.outputPrice,
+ totalPrice: input.totalPrice,
+ unit: input.unit,
+ tokenizerId: input.tokenizerId,
+ tokenizerConfig: input.tokenizerConfig,
+ },
+ });
+ }),
});