Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

refactor(ui): port the create key form off antd Form onto react-hook-form (#37442)

yuneng-jiang963c7fb0d4a5
diff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.json
index 3f32048cac1..b0a4d258ea8 100644
--- a/ui/litellm-dashboard/eslint-suppressions.json
+++ b/ui/litellm-dashboard/eslint-suppressions.json
@@ -2332,9 +2332,6 @@
"local/filename-pascal-case": {
"count": 1
},
- "local/no-complex-jsx-arrow": {
- "count": 2
- },
"max-lines": {
"count": 1
},
diff --git a/ui/litellm-dashboard/src/components/common_components/MountedFormField.tsx b/ui/litellm-dashboard/src/components/common_components/MountedFormField.tsx
new file mode 100644
index 00000000000..8a92873495c
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/common_components/MountedFormField.tsx
@@ -0,0 +1,146 @@
+"use client";
+
+import * as React from "react";
+import {
+ Controller,
+ type Control,
+ type ControllerProps,
+ type RegisterOptions,
+ type UseFormGetValues,
+} from "react-hook-form";
+
+import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/shared/form/field";
+
+export type MountedFormValues = Record<string, unknown>;
+
+export interface MountRegistry {
+ readonly register: (name: string) => () => void;
+ readonly mountedNames: () => readonly string[];
+}
+
+export interface MountedFormContextValue {
+ readonly control: Control<MountedFormValues>;
+ readonly registry: MountRegistry;
+}
+
+const missingProvider = (): never => {
+ throw new Error("MountedFormField requires a MountedFormProvider ancestor");
+};
+
+const MountedFormContext = React.createContext<MountedFormContextValue>({
+ get control(): Control<MountedFormValues> {
+ return missingProvider();
+ },
+ registry: {
+ register: missingProvider,
+ mountedNames: missingProvider,
+ },
+});
+
+export const MountedFormProvider = MountedFormContext.Provider;
+
+export const useMountRegistry = (): MountRegistry => {
+ const counts = React.useRef<Map<string, number>>(new Map());
+ return React.useMemo(
+ () => ({
+ register: (name: string) => {
+ counts.current.set(name, (counts.current.get(name) ?? 0) + 1);
+ return () => {
+ const remaining = (counts.current.get(name) ?? 0) - 1;
+ if (remaining > 0) {
+ counts.current.set(name, remaining);
+ } else {
+ counts.current.delete(name);
+ }
+ };
+ },
+ mountedNames: () => Array.from(counts.current.keys()),
+ }),
+ [],
+ );
+};
+
+export const projectMountedValues = (
+ registry: MountRegistry,
+ getValues: UseFormGetValues<MountedFormValues>,
+): MountedFormValues => {
+ const names = [...registry.mountedNames()];
+ const values = getValues(names);
+ return Object.fromEntries(names.map((name, index) => [name, values[index]]));
+};
+
+export type MountedFieldControlProps = {
+ readonly id: string;
+ readonly name: string;
+ readonly value: unknown;
+ readonly onChange: (...event: unknown[]) => void;
+ readonly onBlur: () => void;
+ readonly "aria-required": "true" | undefined;
+ readonly "aria-invalid": "true" | undefined;
+ readonly "aria-describedby": string | undefined;
+};
+
+export interface MountedFormFieldProps {
+ readonly name: string;
+ readonly label?: React.ReactNode;
+ readonly help?: React.ReactNode;
+ readonly required?: boolean;
+ readonly rules?: Omit<
+ RegisterOptions<MountedFormValues, string>,
+ "valueAsNumber" | "valueAsDate" | "setValueAs" | "disabled"
+ >;
+ readonly defaultValue?: unknown;
+ readonly bare?: boolean;
+ readonly className?: string;
+ readonly children: (control: MountedFieldControlProps) => React.ReactNode;
+}
+
+export const MountedFormField: React.FC<MountedFormFieldProps> = ({
+ name,
+ label,
+ help,
+ required,
+ rules,
+ defaultValue,
+ bare,
+ className,
+ children,
+}) => {
+ const { control, registry } = React.useContext(MountedFormContext);
+ React.useEffect(() => registry.register(name), [registry, name]);
+
+ const helpId = `${name}_help`;
+ const hasHelp = help !== undefined && help !== null;
+
+ const renderField: ControllerProps<MountedFormValues, string>["render"] = ({ field, fieldState }) => {
+ const invalid = fieldState.error !== undefined;
+ const controlProps: MountedFieldControlProps = {
+ id: name,
+ name: field.name,
+ value: field.value,
+ onChange: field.onChange,
+ onBlur: field.onBlur,
+ "aria-required": required ? "true" : undefined,
+ "aria-invalid": invalid ? "true" : undefined,
+ "aria-describedby": hasHelp || invalid ? helpId : undefined,
+ };
+
+ if (bare) {
+ return <>{children(controlProps)}</>;
+ }
+
+ return (
+ <Field data-invalid={invalid || undefined} className={className}>
+ {label !== undefined && <FieldLabel htmlFor={name}>{label}</FieldLabel>}
+ {children(controlProps)}
+ {hasHelp ? (
+ <FieldDescription id={helpId}>{help}</FieldDescription>
+ ) : (
+ <FieldError id={helpId} errors={[fieldState.error]} />
+ )}
+ </Field>
+ );
+ };
+
+ return <Controller control={control} name={name} rules={rules} defaultValue={defaultValue} render={renderField} />;
+};
diff --git a/ui/litellm-dashboard/src/components/common_components/check_openapi_schema.tsx b/ui/litellm-dashboard/src/components/common_components/check_openapi_schema.tsx
index bbe6f4f46a0..2bcd516eb7b 100644
--- a/ui/litellm-dashboard/src/components/common_components/check_openapi_schema.tsx
+++ b/ui/litellm-dashboard/src/components/common_components/check_openapi_schema.tsx
@@ -1,10 +1,12 @@
import React, { useState, useEffect } from "react";
-import { Form, Input as AntdInput, InputNumber, Select } from "antd";
+import { Input as AntdInput, InputNumber, Select } from "antd";
import { Input } from "@/components/ui/input";
import { InfoCircleOutlined } from "@ant-design/icons";
import { Tooltip } from "antd";
+import type { UseFormSetValue } from "react-hook-form";
import { getOpenAPISchema } from "../networking";
import { formatLabel } from "@/utils/textUtils";
+import { MountedFormField, type MountedFormValues } from "./MountedFormField";
interface SchemaProperty {
type?: string;
@@ -25,13 +27,13 @@ interface OpenAPISchema {
interface SchemaFormFieldsProps {
schemaComponent: string;
excludedFields?: string[];
- form: any;
+ setValue: UseFormSetValue<MountedFormValues>;
overrideLabels?: { [key: string]: string };
overrideTooltips?: { [key: string]: string };
customValidation?: {
- [key: string]: (rule: any, value: any) => Promise<void>;
+ [key: string]: (rule: unknown, value: unknown) => Promise<void>;
};
- defaultValues?: { [key: string]: any };
+ defaultValues?: { [key: string]: unknown };
}
// Define which fields should be parsed as JSON
@@ -53,6 +55,10 @@ const validateJSON = (value: string): boolean => {
}
};
+const isBlank = (value: unknown): boolean => value === undefined || value === null || value === "";
+
+const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error));
+
const getFieldHelp = (key: string, property: SchemaProperty, type: string): string => {
// Default help text based on type
const defaultHelp =
@@ -99,7 +105,7 @@ const getFieldHelp = (key: string, property: SchemaProperty, type: string): stri
const SchemaFormFields: React.FC<SchemaFormFieldsProps> = ({
schemaComponent,
excludedFields = [],
- form,
+ setValue,
overrideLabels = {},
overrideTooltips = {},
customValidation = {},
@@ -120,14 +126,11 @@ const SchemaFormFields: React.FC<SchemaFormFieldsProps> = ({
setSchemaProperties(componentSchema);
- const defaultFormValues: { [key: string]: any } = {};
Object.keys(componentSchema.properties)
.filter((key) => !excludedFields.includes(key) && defaultValues[key] !== undefined)
.forEach((key) => {
- defaultFormValues[key] = defaultValues[key];
+ setValue(key, defaultValues[key]);
});
-
- form.setFieldsValue(defaultFormValues);
} catch (error) {
console.error("Schema fetch error:", error);
setError(error instanceof Error ? error.message : "Failed to fetch schema");
@@ -135,7 +138,7 @@ const SchemaFormFields: React.FC<SchemaFormFieldsProps> = ({
};
fetchOpenAPISchema();
- }, [schemaComponent, form, excludedFields]);
+ }, [schemaComponent, setValue, excludedFields]);
const getPropertyType = (property: SchemaProperty): string => {
if (property.type) {
@@ -156,22 +159,25 @@ const SchemaFormFields: React.FC<SchemaFormFieldsProps> = ({
const label = overrideLabels[key] || property.title || formatLabel(key);
const tooltip = overrideTooltips[key] || property.description;
- const rules = [];
- if (isRequired) {
- rules.push({ required: true, message: `${label} is required` });
- }
- if (customValidation[key]) {
- rules.push({ validator: customValidation[key] });
- }
- if (isJSONField(key, property)) {
- rules.push({
- validator: async (_: any, value: string) => {
- if (value && !validateJSON(value)) {
- throw new Error("Please enter valid JSON");
+ const validate = {
+ ...(isRequired && {
+ required: (value: unknown) => (isBlank(value) ? `${label} is required` : true),
+ }),
+ ...(customValidation[key] && {
+ custom: async (value: unknown) => {
+ try {
+ await customValidation[key](null, value);
+ return true;
+ } catch (thrown) {
+ return messageOf(thrown);
}
},
- });
- }
+ }),
+ ...(isJSONField(key, property) && {
+ json: (value: unknown) =>
+ value && !validateJSON(value as string) ? "Please enter valid JSON" : (true as const),
+ }),
+ };
const formLabel = tooltip ? (
<span>
@@ -184,44 +190,63 @@ const SchemaFormFields: React.FC<SchemaFormFieldsProps> = ({
label
);
- let inputComponent;
- if (isJSONField(key, property)) {
- inputComponent = <AntdInput.TextArea rows={4} placeholder="Enter as JSON" className="font-mono" />;
- } else if (property.enum) {
- inputComponent = (
- <Select>
- {property.enum.map((value) => (
- <Select.Option key={value} value={value}>
- {value}
- </Select.Option>
- ))}
- </Select>
- );
- } else if (type === "number" || type === "integer") {
- inputComponent = <InputNumber style={{ width: "100%" }} precision={type === "integer" ? 0 : undefined} />;
- } else if (key === "duration") {
- inputComponent = <Input placeholder="eg: 30s, 30h, 30d" />;
- } else {
- inputComponent = <Input placeholder={tooltip || ""} />;
- }
-
return (
- <Form.Item
+ <MountedFormField
key={key}
label={formLabel}
name={key}
className="mt-8"
- rules={rules}
- initialValue={defaultValues[key]}
- help={<div className="text-xs text-gray-500">{getFieldHelp(key, property, type)}</div>}
+ required={isRequired}
+ rules={Object.keys(validate).length > 0 ? { validate } : undefined}
+ defaultValue={defaultValues[key]}
+ help={<div className="text-xs text-muted-foreground">{getFieldHelp(key, property, type)}</div>}
>
- {inputComponent}
- </Form.Item>
+ {(control) => {
+ if (isJSONField(key, property)) {
+ return (
+ <AntdInput.TextArea
+ {...control}
+ value={control.value as string | undefined}
+ rows={4}
+ placeholder="Enter as JSON"
+ className="font-mono"
+ />
+ );
+ }
+ if (property.enum) {
+ return (
+ <Select {...control} value={control.value as string | undefined}>
+ {property.enum.map((value) => (
+ <Select.Option key={value} value={value}>
+ {value}
+ </Select.Option>
+ ))}
+ </Select>
+ );
+ }
+ if (type === "number" || type === "integer") {
+ return (
+ <InputNumber
+ {...control}
+ value={control.value as number | undefined}
+ style={{ width: "100%" }}
+ precision={type === "integer" ? 0 : undefined}
+ />
+ );
+ }
+ if (key === "duration") {
+ return (
+ <Input {...control} value={(control.value as string | undefined) ?? ""} placeholder="eg: 30s, 30h, 30d" />
+ );
+ }
+ return <Input {...control} value={(control.value as string | undefined) ?? ""} placeholder={tooltip || ""} />;
+ }}
+ </MountedFormField>
);
};
if (error) {
- return <div className="text-red-500">Error: {error}</div>;
+ return <div className="text-destructive">Error: {error}</div>;
}
if (!schemaProperties?.properties) {
diff --git a/ui/litellm-dashboard/src/components/organisms/create_key_button.integration.test.tsx b/ui/litellm-dashboard/src/components/organisms/create_key_button.integration.test.tsx
index 9788d365fd0..3069d25a18b 100644
--- a/ui/litellm-dashboard/src/components/organisms/create_key_button.integration.test.tsx
+++ b/ui/litellm-dashboard/src/components/organisms/create_key_button.integration.test.tsx
@@ -875,4 +875,70 @@ describe("CreateKey", () => {
expect(screen.queryByRole("button", { name: /Optional Settings/i })).not.toBeInTheDocument();
});
});
+
+ describe("writers outside the submit path", () => {
+ it("lets the selected user win over the search text typed into the same field", async () => {
+ vi.mocked(userFilterUICall).mockResolvedValue([
+ { user_id: "u-77", user_email: "[email protected]" },
+ ] as unknown as Awaited<ReturnType<typeof userFilterUICall>>);
+
+ await openModal();
+ await userEvent.click(screen.getByRole("radio", { name: "Another User" }));
+ await nameTheKey();
+
+ await userEvent.type(antdSearchInput(await screen.findByText("Type email to search for users")), "alice");
+ await userEvent.click(await screen.findByText("[email protected] (u-77)"));
+ await submit();
+
+ expect((await createdPayload()).user_id).toBe("u-77");
+ });
+
+ it("surfaces the required message on a field that carries no help text", async () => {
+ await openModal();
+ await userEvent.click(screen.getByRole("radio", { name: "Another User" }));
+ await nameTheKey();
+ await submit();
+
+ expect(
+ await screen.findByText("Please input the user ID of the user you are assigning the key to"),
+ ).toBeInTheDocument();
+ expect(vi.mocked(keyCreateCall)).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("validation follows the mounted set", () => {
+ it("submits an over-ceiling budget typed into a section the user closed again, omitting the key", async () => {
+ await openModal({ team: { team_id: "team-1", max_budget: 10 } as unknown as Team });
+ await nameTheKey();
+ await openSection(/Optional Settings/i);
+ await userEvent.type(await screen.findByLabelText(/Max Budget \(USD\)/), "50");
+ await openSection(/Optional Settings/i);
+ await submit();
+
+ const payload = await createdPayload();
+ expect(payload).not.toHaveProperty("max_budget");
+ expect(payload.key_alias).toBe("contract-key");
+ });
+ });
+
+ describe("submit gestures", () => {
+ it("creates the key when Enter is pressed inside a text field", async () => {
+ await openModal();
+ await userEvent.type(await screen.findByLabelText(/Key Name/), "enter-key{Enter}");
+
+ expect((await createdPayload()).key_alias).toBe("enter-key");
+ });
+ });
+
+ describe("switch coercion", () => {
+ it("sends enable_prompt_caching as a boolean once the switch is on", async () => {
+ await openModal();
+ await nameTheKey();
+ await openSection(/Optional Settings/i);
+ await userEvent.click(await screen.findByLabelText("Enable Prompt Caching"));
+ await submit();
+
+ expect((await createdPayload()).enable_prompt_caching).toBe(true);
+ });
+ });
});
diff --git a/ui/litellm-dashboard/src/components/organisms/create_key_button.tsx b/ui/litellm-dashboard/src/components/organisms/create_key_button.tsx
index 77ef31e0ede..ad7869202dc 100644
--- a/ui/litellm-dashboard/src/components/organisms/create_key_button.tsx
+++ b/ui/litellm-dashboard/src/components/organisms/create_key_button.tsx
@@ -12,22 +12,13 @@ import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Input } from "@/components/ui/input";
-import {
- Button as Button2,
- Form,
- Input as AntdInput,
- Modal,
- Radio,
- Select,
- Switch,
- Tag,
- Tooltip,
- Typography,
-} from "antd";
+import { Field, FieldLabel } from "@/components/shared/form/field";
+import { Button as Button2, Input as AntdInput, Modal, Radio, Select, Switch, Tag, Tooltip, Typography } from "antd";
import { ChevronDown } from "lucide-react";
import { useDebouncedCallback } from "@tanstack/react-pacer/debouncer";
import { DEBOUNCE_WAIT_MS } from "@/utils/debounceConstants";
-import React, { useEffect, useState } from "react";
+import React, { useEffect, useMemo, useState } from "react";
+import { type Control, useForm, useWatch, type UseFormSetValue } from "react-hook-form";
import { rolesWithWriteAccess } from "../../utils/roles";
import AgentSelector from "../agent_management/AgentSelector";
import AccessGroupSelector from "../common_components/AccessGroupSelector";
@@ -35,6 +26,13 @@ import BudgetDurationDropdown from "../common_components/budget_duration_dropdow
import SchemaFormFields from "../common_components/check_openapi_schema";
import KeyLifecycleSettings from "../common_components/KeyLifecycleSettings";
import ModelAliasManager from "../common_components/ModelAliasManager";
+import {
+ MountedFormField,
+ MountedFormProvider,
+ projectMountedValues,
+ useMountRegistry,
+ type MountedFormValues,
+} from "../common_components/MountedFormField";
import PassThroughRoutesSelector from "../common_components/PassThroughRoutesSelector";
import PremiumLoggingSettings from "../common_components/PremiumLoggingSettings";
import RateLimitTypeFormItem from "../common_components/RateLimitTypeFormItem";
@@ -78,7 +76,46 @@ const { Option } = Select;
const SECTION_HEADER_CLASS = "group/section flex w-full items-center justify-between px-4 py-3 text-left";
const SECTION_CHEVRON_CLASS =
- "size-5 shrink-0 text-gray-500 transition-transform group-data-[panel-open]/section:rotate-180";
+ "size-5 shrink-0 text-muted-foreground transition-transform group-data-[panel-open]/section:rotate-180";
+
+type FieldWrite = (value: unknown) => void;
+
+type McpSelectorValue = { servers: string[]; accessGroups: string[]; toolsets?: string[] };
+
+type AgentSelectorValue = { agents: string[]; accessGroups: string[] };
+
+const isBlank = (value: unknown): boolean => value === undefined || value === null || value === "";
+
+const requiredRule = (required: boolean, message: string) => ({
+ validate: (value: unknown) => (required && isBlank(value) ? message : true),
+});
+
+const ceilingRule = (ceiling: number | null | undefined, message: (limit: number) => string) => ({
+ validate: (value: unknown) =>
+ value && ceiling !== null && ceiling !== undefined && (value as number) > ceiling ? message(ceiling) : true,
+});
+
+interface McpToolPermissionsFieldProps {
+ readonly accessToken: string;
+ readonly control: Control<MountedFormValues>;
+ readonly setValue: UseFormSetValue<MountedFormValues>;
+}
+
+const McpToolPermissionsField: React.FC<McpToolPermissionsFieldProps> = ({ accessToken, control, setValue }) => {
+ const selection = useWatch({ control, name: "allowed_mcp_servers_and_groups" }) as { servers?: string[] } | undefined;
+ const toolPermissions = useWatch({ control, name: "mcp_tool_permissions" }) as Record<string, string[]> | undefined;
+
+ return (
+ <div className="mt-6">
+ <MCPToolPermissions
+ accessToken={accessToken}
+ selectedServers={(selection?.servers || []).filter((s: string) => s !== NO_MCP_SERVERS_SENTINEL)}
+ toolPermissions={toolPermissions || {}}
+ onChange={(toolPerms) => setValue("mcp_tool_permissions", toolPerms)}
+ />
+ </div>
+ );
+};
/**
* Interface for pre-filling the create key form from URL parameters
@@ -176,7 +213,21 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
const disableCustomApiKeys = Boolean(uiSettingsData?.values?.disable_custom_api_keys);
const tagOptions = tagsData ? Object.values(tagsData).map((tag) => ({ value: tag.name, label: tag.name })) : [];
const queryClient = useQueryClient();
- const [form] = Form.useForm();
+ const [formDefaults] = useState<MountedFormValues>(() => ({
+ team_id: team ? team.team_id : null,
+ key_type: "llm_api",
+ tpm_limit_type: null,
+ rpm_limit_type: null,
+ mcp_tool_permissions: {},
+ duration: "",
+ }));
+ const form = useForm<MountedFormValues>({
+ mode: "onChange",
+ shouldUnregister: false,
+ defaultValues: formDefaults,
+ });
+ const registry = useMountRegistry();
+ const mountedForm = useMemo(() => ({ control: form.control, registry }), [form.control, registry]);
const [isModalVisible, setIsModalVisible] = useState(false);
const [apiKey, setApiKey] = useState(null);
const [userModels, setUserModels] = useState<string[]>([]);
@@ -208,10 +259,10 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
const [routerSettingsKey, setRouterSettingsKey] = useState<number>(0);
const [agentsList, setAgentsList] = useState<{ agent_id: string; agent_name: string }[]>([]);
const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
- const selectedModels: string[] = Form.useWatch("models", form) ?? [];
+ const selectedModels: string[] = (useWatch({ control: form.control, name: "models" }) as string[] | undefined) ?? [];
const handleOk = () => {
setIsModalVisible(false);
- form.resetFields();
+ form.reset(formDefaults);
setLoggingSettings([]);
setDisabledCallbacks([]);
setKeyType("llm_api");
@@ -233,7 +284,7 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
setIsModalVisible(false);
setApiKey(null);
setSelectedCreateKeyTeam(null);
- form.resetFields();
+ form.reset(formDefaults);
setLoggingSettings([]);
setDisabledCallbacks([]);
setKeyType("llm_api");
@@ -348,14 +399,14 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
const selectedTeam = teams?.find((t) => t.team_id === prefillData.team_id) || null;
if (selectedTeam) {
setSelectedCreateKeyTeam(selectedTeam);
- form.setFieldsValue({ team_id: prefillData.team_id });
+ form.setValue("team_id", prefillData.team_id);
}
// Silently ignore invalid team_id - don't prefill with a team user doesn't have access to
}
// Set key alias
if (prefillData.key_alias) {
- form.setFieldsValue({ key_alias: prefillData.key_alias });
+ form.setValue("key_alias", prefillData.key_alias);
}
// Defer model selection until we load the allowed model list.
@@ -366,7 +417,7 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
// Set key type
if (prefillData.key_type) {
setKeyType(prefillData.key_type);
- form.setFieldsValue({ key_type: prefillData.key_type });
+ form.setValue("key_type", prefillData.key_type);
}
}
}
@@ -376,7 +427,7 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
const isTeamSelectionRequired = modelsToPick.includes("no-default-models");
const isFormDisabled = isTeamSelectionRequired && !selectedCreateKeyTeam;
- const handleCreate = async (formValues: Record<string, any>) => {
+ const handleCreate = async (formValues: MountedFormValues) => {
try {
const input: KeyCreateInput = {
formValues,
@@ -425,7 +476,7 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
setApiKey(response["key"]);
toast.success("Virtual Key Created");
- form.resetFields();
+ form.reset(formDefaults);
setBudgetLimits([]);
setTagRateLimits([]);
setBudgetFallbacks({});
@@ -437,6 +488,8 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
}
};
+ const handleSubmit = form.handleSubmit(() => handleCreate(projectMountedValues(registry, form.getValues)));
+
// Fetch available models when team or auth changes.
// Note: Model prefill from URL params is handled by the useEffect below, which
// watches for pendingPrefillModels + modelsToPick to both be populated.
@@ -446,7 +499,7 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
const project = projects?.find((p) => p.project_id === selectedProjectId);
const projectModels = project?.models ?? [];
setModelsToPick(projectModels);
- form.setFieldValue("models", []);
+ form.setValue("models", []);
return;
}
if (userID && userRole && accessToken) {
@@ -459,10 +512,10 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
}
// Only clear models if we don't have pending prefill models
if (!pendingPrefillModels) {
- form.setFieldValue("models", []);
+ form.setValue("models", []);
}
// Clear MCP server selection when team changes (available servers may differ)
- form.setFieldValue("allowed_mcp_servers_and_groups", { servers: [], accessGroups: [] });
+ form.setValue("allowed_mcp_servers_and_groups", { servers: [], accessGroups: [] });
}, [selectedCreateKeyTeam, selectedProjectId, accessToken, userID, userRole, form]);
// Apply deferred model prefill once the available model list arrives.
@@ -477,7 +530,7 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
const validModels = pendingPrefillModels.filter((model) => modelsToPick.includes(model));
if (validModels.length > 0) {
- form.setFieldsValue({ models: validModels });
+ form.setValue("models", validModels);
}
setPendingPrefillModels(null);
}, [pendingPrefillModels, modelsToPick, form]);
@@ -492,13 +545,13 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
const projectTeam = teams.find((t) => t.team_id === project.team_id) || null;
if (projectTeam) {
setSelectedCreateKeyTeam(projectTeam);
- form.setFieldValue("team_id", projectTeam.team_id);
+ form.setValue("team_id", projectTeam.team_id);
}
}, [teams, selectedProjectId, projects]);
// Add a callback function to handle user creation
const handleUserCreated = (userId: string) => {
- form.setFieldsValue({ user_id: userId });
+ form.setValue("user_id", userId);
setIsCreateUserModalVisible(false);
};
@@ -537,9 +590,51 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
const handleUserSelect = (_value: string, option: UserOption): void => {
const selectedUser = option.user;
- form.setFieldsValue({
- user_id: selectedUser.user_id,
- });
+ form.setValue("user_id", selectedUser.user_id);
+ };
+
+ const changeOrganization = (write: FieldWrite) => (orgId: string) => {
+ write(orgId);
+ setSelectedOrganizationId(orgId || null);
+ // Clear team and project when org changes
+ setSelectedCreateKeyTeam(null);
+ setSelectedProjectId(null);
+ form.setValue("team_id", undefined);
+ form.setValue("project_id", undefined);
+ };
+
+ const selectTeam = (team: Team | null) => {
+ setSelectedCreateKeyTeam(team);
+ setSelectedProjectId(null);
+ form.setValue("project_id", undefined);
+ // Auto-populate org from team for non-admin users
+ if (team?.organization_id) {
+ setSelectedOrganizationId(team.organization_id);
+ form.setValue("organization_id", team.organization_id);
+ } else if (!team) {
+ setSelectedOrganizationId(null);
+ form.setValue("organization_id", undefined);
+ }
+ };
+
+ const changeProject = (write: FieldWrite) => (projectId: string) => {
+ write(projectId);
+ if (!projectId) {
+ setSelectedProjectId(null);
+ setSelectedCreateKeyTeam(null);
+ form.setValue("team_id", undefined);
+ return;
+ }
+ setSelectedProjectId(projectId);
+ };
+
+ const changeKeyType = (write: FieldWrite) => (value: string) => {
+ write(value);
+ setKeyType(value);
+ // Clear models field and disable if management or read_only
+ if (value === "management" || value === "read_only") {
+ form.setValue("models", []);
+ }
};
return (
@@ -550,593 +645,553 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
</Button>
)}
<Modal open={isModalVisible} width={1000} footer={null} onOk={handleOk} onCancel={handleCancel}>
- <Form form={form} onFinish={handleCreate} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} labelAlign="left">
- {/* Section 1: Key Ownership */}
- <div className="mb-8">
- <h3 className="text-lg font-medium text-gray-900 mb-4">Key Ownership</h3>
- <Form.Item
- label={
- <span>
- Owned By{" "}
- <Tooltip title="Select who will own this Virtual Key">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- className="mb-4"
- >
- <Radio.Group onChange={(e) => setKeyOwner(e.target.value)} value={keyOwner}>
- <Radio value="you">You</Radio>
- <Radio value="service_account">Service Account</Radio>
- {userRole === "Admin" && <Radio value="another_user">Another User</Radio>}
- <Radio value="agent">
- Agent <Tag color="purple">New</Tag>
- </Radio>
- </Radio.Group>
- </Form.Item>
-
- {keyOwner === "another_user" && (
- <Form.Item
- label={
+ <MountedFormProvider value={mountedForm}>
+ <form onSubmit={handleSubmit}>
+ {/* Section 1: Key Ownership */}
+ <div className="mb-8">
+ <h3 className="text-lg font-medium text-foreground mb-4">Key Ownership</h3>
+ <Field className="mb-4">
+ <FieldLabel>
<span>
- User ID{" "}
- <Tooltip title="The user who will own this key and be responsible for its usage">
+ Owned By{" "}
+ <Tooltip title="Select who will own this Virtual Key">
<InfoCircleOutlined style={{ marginLeft: "4px" }} />
</Tooltip>
</span>
- }
- name="user_id"
- className="mt-4"
- rules={[
- {
- required: keyOwner === "another_user",
- message: `Please input the user ID of the user you are assigning the key to`,
- },
- ]}
- >
- <div>
- <div style={{ display: "flex", marginBottom: "8px" }}>
- <Select
- showSearch
- placeholder="Type email to search for users"
- filterOption={false}
- onSearch={handleUserSearch}
- onSelect={(value, option) => handleUserSelect(value, option as UserOption)}
- options={userOptions}
- loading={userSearchLoading}
- allowClear
- style={{ width: "100%" }}
- notFoundContent={userSearchLoading ? "Searching..." : "No users found"}
- />
- <Button2 onClick={() => setIsCreateUserModalVisible(true)} style={{ marginLeft: "8px" }}>
- Create User
- </Button2>
- </div>
- <div className="text-xs text-gray-500">Search by email to find users</div>
- </div>
- </Form.Item>
- )}
- {keyOwner === "agent" && (
- <div className="mt-4 p-4 bg-purple-50 border border-purple-200 rounded-md">
- <div className="mb-3">
- <span className="text-sm font-medium text-gray-700">
- Select Agent <span className="text-red-500">*</span>
- </span>
- </div>
- <Select
- showSearch
- placeholder="Select an agent"
- style={{ width: "100%" }}
- value={selectedAgentId}
- onChange={(value) => setSelectedAgentId(value)}
- filterOption={(input, option) =>
- (option?.label as string)?.toLowerCase().includes(input.toLowerCase())
+ </FieldLabel>
+ <Radio.Group onChange={(e) => setKeyOwner(e.target.value)} value={keyOwner}>
+ <Radio value="you">You</Radio>
+ <Radio value="service_account">Service Account</Radio>
+ {userRole === "Admin" && <Radio value="another_user">Another User</Radio>}
+ <Radio value="agent">
+ Agent <Tag color="purple">New</Tag>
+ </Radio>
+ </Radio.Group>
+ </Field>
+
+ {keyOwner === "another_user" && (
+ <MountedFormField
+ label={
+ <span>
+ User ID{" "}
+ <Tooltip title="The user who will own this key and be responsible for its usage">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
}
- options={agentsList.map((a) => ({
- label: a.agent_name || a.agent_id,
- value: a.agent_id,
- }))}
- />
- <div className="text-xs text-gray-500 mt-2">
- This key will be used by the selected agent to make requests to LiteLLM
+ name="user_id"
+ className="mt-4"
+ required
+ rules={requiredRule(
+ keyOwner === "another_user",
+ `Please input the user ID of the user you are assigning the key to`,
+ )}
+ >
+ {(control) => (
+ <div
+ id={control.id}
+ aria-required={control["aria-required"]}
+ aria-invalid={control["aria-invalid"]}
+ aria-describedby={control["aria-describedby"]}
+ onChange={control.onChange}
+ >
+ <div style={{ display: "flex", marginBottom: "8px" }}>
+ <Select
+ showSearch
+ placeholder="Type email to search for users"
+ filterOption={false}
+ onSearch={handleUserSearch}
+ onSelect={(value, option) => handleUserSelect(value, option as UserOption)}
+ options={userOptions}
+ loading={userSearchLoading}
+ allowClear
+ style={{ width: "100%" }}
+ notFoundContent={userSearchLoading ? "Searching..." : "No users found"}
+ />
+ <Button2 onClick={() => setIsCreateUserModalVisible(true)} style={{ marginLeft: "8px" }}>
+ Create User
+ </Button2>
+ </div>
+ <div className="text-xs text-muted-foreground">Search by email to find users</div>
+ </div>
+ )}
+ </MountedFormField>
+ )}
+ {keyOwner === "agent" && (
+ <div className="mt-4 p-4 bg-purple-50 border border-purple-200 rounded-md">
+ <div className="mb-3">
+ <span className="text-sm font-medium text-foreground">
+ Select Agent <span className="text-destructive">*</span>
+ </span>
+ </div>
+ <Select
+ showSearch
+ placeholder="Select an agent"
+ style={{ width: "100%" }}
+ value={selectedAgentId}
+ onChange={(value) => setSelectedAgentId(value)}
+ filterOption={(input, option) =>
+ (option?.label as string)?.toLowerCase().includes(input.toLowerCase())
+ }
+ options={agentsList.map((a) => ({
+ label: a.agent_name || a.agent_id,
+ value: a.agent_id,
+ }))}
+ />
+ <div className="text-xs text-muted-foreground mt-2">
+ This key will be used by the selected agent to make requests to LiteLLM
+ </div>
</div>
- </div>
- )}
- <Form.Item
- label={
- <span>
- Organization{" "}
- <Tooltip title="The organization this key belongs to. Selecting an organization filters the available teams.">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="organization_id"
- className="mt-4"
- >
- <OrganizationDropdown
- organizations={organizations}
- loading={isOrganizationsLoading}
- disabled={userRole !== "Admin"}
- onChange={(orgId) => {
- setSelectedOrganizationId(orgId || null);
- // Clear team and project when org changes
- setSelectedCreateKeyTeam(null);
- setSelectedProjectId(null);
- form.setFieldValue("team_id", undefined);
- form.setFieldValue("project_id", undefined);
- }}
- />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Team{" "}
- <Tooltip title="The team this key belongs to, which determines available models and budget limits">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="team_id"
- initialValue={team ? team.team_id : null}
- className="mt-4"
- rules={[
- {
- required: keyOwner === "service_account",
- message: "Please select a team for the service account",
- },
- ]}
- help={keyOwner === "service_account" ? "required" : ""}
- >
- <TeamDropdown
- disabled={selectedProjectId !== null}
- organizationId={selectedOrganizationId}
- onTeamSelect={(team) => {
- setSelectedCreateKeyTeam(team);
- setSelectedProjectId(null);
- form.setFieldValue("project_id", undefined);
- // Auto-populate org from team for non-admin users
- if (team?.organization_id) {
- setSelectedOrganizationId(team.organization_id);
- form.setFieldValue("organization_id", team.organization_id);
- } else if (!team) {
- setSelectedOrganizationId(null);
- form.setFieldValue("organization_id", undefined);
- }
- }}
- />
- </Form.Item>
- {enableProjectsUI && (
- <Form.Item
+ )}
+ <MountedFormField
label={
<span>
- Project{" "}
- <Tooltip title="Assign this key to a project. Selecting a project will lock the team to the project's team.">
+ Organization{" "}
+ <Tooltip title="The organization this key belongs to. Selecting an organization filters the available teams.">
<InfoCircleOutlined style={{ marginLeft: "4px" }} />
</Tooltip>
</span>
}
- name="project_id"
+ name="organization_id"
className="mt-4"
>
- <ProjectDropdown
- projects={projects}
- teamId={selectedCreateKeyTeam?.team_id}
- loading={isProjectsLoading || !teams}
- onChange={(projectId) => {
- if (!projectId) {
- setSelectedProjectId(null);
- setSelectedCreateKeyTeam(null);
- form.setFieldValue("team_id", undefined);
- return;
- }
- setSelectedProjectId(projectId);
- }}
- />
- </Form.Item>
- )}
- </div>
-
- {/* Show message when team selection is required */}
- {isFormDisabled && (
- <div className="mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md">
- <p className="text-blue-800 text-sm">
- Please select a team to continue configuring your Virtual Key. If you do not see any teams, please
- contact your Proxy Admin to either provide you with access to models or to add you to a team.
- </p>
- </div>
- )}
-
- {/* Section 2: Key Details */}
- {!isFormDisabled && (
- <div className="mb-8">
- <h3 className="text-lg font-medium text-gray-900 mb-4">Key Details</h3>
- <Form.Item
+ {(control) => (
+ <OrganizationDropdown
+ id={control.id}
+ value={control.value as string | undefined}
+ organizations={organizations}
+ loading={isOrganizationsLoading}
+ disabled={userRole !== "Admin"}
+ onChange={changeOrganization(control.onChange)}
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField
label={
<span>
- {keyOwner === "you" || keyOwner === "another_user" ? "Key Name" : "Service Account ID"}{" "}
- <Tooltip
- title={
- keyOwner === "you" || keyOwner === "another_user"
- ? "A descriptive name to identify this key"
- : "Unique identifier for this service account"
- }
- >
+ Team{" "}
+ <Tooltip title="The team this key belongs to, which determines available models and budget limits">
<InfoCircleOutlined style={{ marginLeft: "4px" }} />
</Tooltip>
</span>
}
- name="key_alias"
- rules={[
- {
- required: true,
- message: `Please input a ${keyOwner === "you" ? "key name" : "service account ID"}`,
- },
- ]}
- help="required"
- >
- <Input />
- </Form.Item>
-
- <Form.Item
- label={
- <span>
- Models{" "}
- <Tooltip title="Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team. Leave empty to allow access to all models.">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="models"
- rules={[]}
- help={
- keyType === "management" || keyType === "read_only"
- ? "Models field is disabled for this key type"
- : "optional - leave empty to allow access to all models"
- }
+ name="team_id"
className="mt-4"
+ required={keyOwner === "service_account"}
+ rules={requiredRule(keyOwner === "service_account", "Please select a team for the service account")}
+ help={keyOwner === "service_account" ? "required" : ""}
>
- <Select
- mode="multiple"
- placeholder="Select models"
- style={{ width: "100%" }}
- disabled={keyType === "management" || keyType === "read_only"}
- onChange={(values) => {
- if (values.includes("all-team-models")) {
- form.setFieldsValue({ models: ["all-team-models"] });
- } else if (values.includes("all-proxy-models")) {
- form.setFieldsValue({ models: ["all-proxy-models"] });
- }
- }}
+ {(control) => (
+ <TeamDropdown
+ id={control.id}
+ value={control.value as string | undefined}
+ onChange={control.onChange}
+ disabled={selectedProjectId !== null}
+ organizationId={selectedOrganizationId}
+ onTeamSelect={selectTeam}
+ />
+ )}
+ </MountedFormField>
+ {enableProjectsUI && (
+ <MountedFormField
+ label={
+ <span>
+ Project{" "}
+ <Tooltip title="Assign this key to a project. Selecting a project will lock the team to the project's team.">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="project_id"
+ className="mt-4"
>
- {!selectedProjectId && selectedCreateKeyTeam && (
- <Option key="all-team-models" value="all-team-models">
- All Team Models
- </Option>
- )}
- {!selectedProjectId && !selectedCreateKeyTeam && (
- <Option key="all-proxy-models" value="all-proxy-models">
- All Proxy Models
- </Option>
+ {(control) => (
+ <ProjectDropdown
+ id={control.id}
+ value={control.value as string | undefined}
+ projects={projects}
+ teamId={selectedCreateKeyTeam?.team_id}
+ loading={isProjectsLoading || !teams}
+ onChange={changeProject(control.onChange)}
+ />
)}
- {modelsToPick.map((model: string) => (
- <Option key={model} value={model} disabled={hasAllModelsSentinel(selectedModels)}>
- {getModelDisplayName(model)}
- </Option>
- ))}
- </Select>
- </Form.Item>
-
- <Form.Item
- label={
- <span>
- Key Type{" "}
- <Tooltip title="Select the type of key to determine what routes and operations this key can access">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="key_type"
- initialValue="llm_api"
- className="mt-4"
- >
- <Select
- defaultValue="llm_api"
- placeholder="Select key type"
- style={{ width: "100%" }}
- optionLabelProp="label"
- onChange={(value) => {
- setKeyType(value);
- // Clear models field and disable if management or read_only
- if (value === "management" || value === "read_only") {
- form.setFieldsValue({ models: [] });
- }
- }}
- >
- <Option value="llm_api" label="AI APIs">
- <div style={{ padding: "4px 0" }}>
- <Typography.Text strong>AI APIs</Typography.Text>
- <Typography.Paragraph type="secondary" style={{ fontSize: 11, margin: "2px 0 0" }}>
- Can call only AI API routes (chat/completions, embeddings, etc.)
- </Typography.Paragraph>
- </div>
- </Option>
- <Option value="management" label="Management">
- <div style={{ padding: "4px 0" }}>
- <Typography.Text strong>Management</Typography.Text>
- <Typography.Paragraph type="secondary" style={{ fontSize: 11, margin: "2px 0 0" }}>
- Can call only management routes (user/team/key management)
- </Typography.Paragraph>
- </div>
- </Option>
- <Option value="default" label="Full Access">
- <div style={{ padding: "4px 0" }}>
- <Typography.Text strong>Full Access</Typography.Text>
- <Typography.Paragraph type="secondary" style={{ fontSize: 11, margin: "2px 0 0" }}>
- Can call all routes (AI APIs, Management, and read-only)
- </Typography.Paragraph>
- </div>
- </Option>
- </Select>
- </Form.Item>
+ </MountedFormField>
+ )}
</div>
- )}
- {/* Section 3: Optional Settings */}
- {!isFormDisabled && (
- <div className="mb-8">
- <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
- <h3 className="m-0 text-lg font-medium text-gray-900">
- <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
- Optional Settings
- <ChevronDown className={SECTION_CHEVRON_CLASS} />
- </CollapsibleTrigger>
- </h3>
- <CollapsibleContent className="px-4 pb-3">
- <Form.Item
- className="mt-4"
- label={
- <span>
- Max Budget (USD){" "}
- <Tooltip title="Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="max_budget"
- help={`Budget cannot exceed team max budget: $${team?.max_budget !== null && team?.max_budget !== undefined ? team?.max_budget : "unlimited"}`}
- rules={[
- {
- validator: async (_, value) => {
- if (value && team && team.max_budget !== null && value > team.max_budget) {
- throw new Error(
- `Budget cannot exceed team max budget: $${formatNumberWithCommas(team.max_budget, 4)}`,
- );
- }
- },
- },
- ]}
- >
- <NumericalInput step={0.01} precision={2} width={200} />
- </Form.Item>
- <Form.Item
- className="mt-4"
- label={
- <span>
- Reset Budget{" "}
- <Tooltip title="How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="budget_duration"
- help={`Team Reset Budget: ${team?.budget_duration !== null && team?.budget_duration !== undefined ? team?.budget_duration : "None"}`}
- >
- <BudgetDurationDropdown
- showNeverResets
- placeholder="Not set"
- onChange={(value) => form.setFieldValue("budget_duration", value)}
- />
- </Form.Item>
- <Form.Item
- className="mt-4"
- label={
- <span>
- Budget Windows{" "}
- <Tooltip title="Set multiple independent budget windows (e.g., hourly $10 AND monthly $200). Each window tracks spend separately and resets on its own schedule.">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- >
- <BudgetWindowsEditor value={budgetLimits} onChange={setBudgetLimits} />
- </Form.Item>
- <Form.Item
- className="mt-4"
- label={
- <span>
- Budget Fallbacks{" "}
- <Tooltip title="When a model exceeds its per-model budget (model_max_budget), requests automatically reroute to fallback models instead of failing. Configure per-model budgets in Advanced Settings.">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- >
- <BudgetFallbacksEditor
- key={budgetFallbacksKey}
- value={budgetFallbacks}
- onChange={setBudgetFallbacks}
- availableModels={modelsToPick}
- />
- </Form.Item>
- <Form.Item
- className="mt-4"
- label={
- <span>
- Tokens per minute Limit (TPM){" "}
- <Tooltip title="Maximum number of tokens this key can process per minute. Helps control usage and costs">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="tpm_limit"
- help={`TPM cannot exceed team TPM limit: ${team?.tpm_limit !== null && team?.tpm_limit !== undefined ? team?.tpm_limit : "unlimited"}`}
- rules={[
- {
- validator: async (_, value) => {
- if (value && team && team.tpm_limit !== null && value > team.tpm_limit) {
- throw new Error(`TPM limit cannot exceed team TPM limit: ${team.tpm_limit}`);
- }
- },
- },
- ]}
- >
- <NumericalInput step={1} width={400} />
- </Form.Item>
- <Form.Item name="tpm_limit_type" initialValue={null} noStyle>
- <RateLimitTypeFormItem type="tpm" name="tpm_limit_type" className="mt-4" showDetailedDescriptions />
- </Form.Item>
- <Form.Item
- className="mt-4"
- label={
- <span>
- Requests per minute Limit (RPM){" "}
- <Tooltip title="Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="rpm_limit"
- help={`RPM cannot exceed team RPM limit: ${team?.rpm_limit !== null && team?.rpm_limit !== undefined ? team?.rpm_limit : "unlimited"}`}
- rules={[
- {
- validator: async (_, value) => {
- if (value && team && team.rpm_limit !== null && value > team.rpm_limit) {
- throw new Error(`RPM limit cannot exceed team RPM limit: ${team.rpm_limit}`);
- }
- },
- },
- ]}
- >
- <NumericalInput step={1} width={400} />
- </Form.Item>
- <Form.Item name="rpm_limit_type" initialValue={null} noStyle>
- <RateLimitTypeFormItem type="rpm" name="rpm_limit_type" className="mt-4" showDetailedDescriptions />
- </Form.Item>
- <Form.Item
- className="mt-4"
- label={
- <span>
- Per-Tag Rate Limits{" "}
- <Tooltip title="Scope rate limits to a request tag so each tag (e.g. a cell or group) gets its own RPM counter. Requests without a matching tag fall back to the key-level limit.">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- >
- <TagRateLimitEditor value={tagRateLimits} onChange={setTagRateLimits} />
- </Form.Item>
- <Form.Item
- className="mt-4"
- label={
- <span>
- Throttle on budget exceeded{" "}
- <Tooltip title="When this key exceeds its max budget, throttle its TPM/RPM to the globally configured percentage instead of blocking access entirely. Requires budget_exceeded_throttle_percentage in litellm_settings and a TPM/RPM limit on the key.">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="throttle_on_budget_exceeded"
- valuePropName="checked"
- >
- <Switch checkedChildren="Yes" unCheckedChildren="No" />
- </Form.Item>
- <Form.Item
- className="mt-4"
- label={
- <span>
- Enable Prompt Caching{" "}
- <Tooltip title="Automatically add prompt caching breakpoints (cache_control markers) to requests made with this key, cutting input cost on repeated prompts. Applies to Anthropic and Bedrock Claude models; requests that already set their own cache_control markers are left untouched.">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="enable_prompt_caching"
- valuePropName="checked"
- >
- <Switch checkedChildren="Yes" unCheckedChildren="No" />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Guardrails{" "}
- <Tooltip title="Apply safety guardrails to this key to filter content or enforce policies">
- <a
- href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"
- target="_blank"
- rel="noopener noreferrer"
- onClick={(e) => e.stopPropagation()} // Prevent accordion from collapsing when clicking link
- >
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </a>
- </Tooltip>
- </span>
- }
- name="guardrails"
- className="mt-4"
- help={
- canEditGuardrails
- ? "Select existing guardrails or enter new ones"
- : "Premium feature - Upgrade to set guardrails by key"
- }
- >
+ {/* Show message when team selection is required */}
+ {isFormDisabled && (
+ <div className="mb-8 p-4 bg-blue-50 border border-blue-200 rounded-md">
+ <p className="text-blue-800 text-sm">
+ Please select a team to continue configuring your Virtual Key. If you do not see any teams, please
+ contact your Proxy Admin to either provide you with access to models or to add you to a team.
+ </p>
+ </div>
+ )}
+
+ {/* Section 2: Key Details */}
+ {!isFormDisabled && (
+ <div className="mb-8">
+ <h3 className="text-lg font-medium text-foreground mb-4">Key Details</h3>
+ <MountedFormField
+ label={
+ <span>
+ {keyOwner === "you" || keyOwner === "another_user" ? "Key Name" : "Service Account ID"}{" "}
+ <Tooltip
+ title={
+ keyOwner === "you" || keyOwner === "another_user"
+ ? "A descriptive name to identify this key"
+ : "Unique identifier for this service account"
+ }
+ >
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="key_alias"
+ required
+ rules={requiredRule(true, `Please input a ${keyOwner === "you" ? "key name" : "service account ID"}`)}
+ help="required"
+ >
+ {(control) => <Input {...control} value={(control.value as string | undefined) ?? ""} />}
+ </MountedFormField>
+
+ <MountedFormField
+ label={
+ <span>
+ Models{" "}
+ <Tooltip title="Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team. Leave empty to allow access to all models.">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="models"
+ help={
+ keyType === "management" || keyType === "read_only"
+ ? "Models field is disabled for this key type"
+ : "optional - leave empty to allow access to all models"
+ }
+ className="mt-4"
+ >
+ {(control) => (
+ <Select
+ {...control}
+ value={control.value as string[] | undefined}
+ mode="multiple"
+ placeholder="Select models"
+ style={{ width: "100%" }}
+ disabled={keyType === "management" || keyType === "read_only"}
+ onChange={(values: string[]) => {
+ control.onChange(values);
+ if (values.includes("all-team-models")) {
+ form.setValue("models", ["all-team-models"]);
+ } else if (values.includes("all-proxy-models")) {
+ form.setValue("models", ["all-proxy-models"]);
+ }
+ }}
+ >
+ {!selectedProjectId && selectedCreateKeyTeam && (
+ <Option key="all-team-models" value="all-team-models">
+ All Team Models
+ </Option>
+ )}
+ {!selectedProjectId && !selectedCreateKeyTeam && (
+ <Option key="all-proxy-models" value="all-proxy-models">
+ All Proxy Models
+ </Option>
+ )}
+ {modelsToPick.map((model: string) => (
+ <Option key={model} value={model} disabled={hasAllModelsSentinel(selectedModels)}>
+ {getModelDisplayName(model)}
+ </Option>
+ ))}
+ </Select>
+ )}
+ </MountedFormField>
+
+ <MountedFormField
+ label={
+ <span>
+ Key Type{" "}
+ <Tooltip title="Select the type of key to determine what routes and operations this key can access">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="key_type"
+ className="mt-4"
+ >
+ {(control) => (
<Select
- mode="tags"
+ {...control}
+ value={control.value as string | undefined}
+ placeholder="Select key type"
style={{ width: "100%" }}
- disabled={!canEditGuardrails}
- placeholder={
- !canEditGuardrails
- ? "Premium feature - Upgrade to set guardrails by key"
- : "Select or enter guardrails"
+ optionLabelProp="label"
+ onChange={changeKeyType(control.onChange)}
+ >
+ <Option value="llm_api" label="AI APIs">
+ <div style={{ padding: "4px 0" }}>
+ <Typography.Text strong>AI APIs</Typography.Text>
+ <Typography.Paragraph type="secondary" style={{ fontSize: 11, margin: "2px 0 0" }}>
+ Can call only AI API routes (chat/completions, embeddings, etc.)
+ </Typography.Paragraph>
+ </div>
+ </Option>
+ <Option value="management" label="Management">
+ <div style={{ padding: "4px 0" }}>
+ <Typography.Text strong>Management</Typography.Text>
+ <Typography.Paragraph type="secondary" style={{ fontSize: 11, margin: "2px 0 0" }}>
+ Can call only management routes (user/team/key management)
+ </Typography.Paragraph>
+ </div>
+ </Option>
+ <Option value="default" label="Full Access">
+ <div style={{ padding: "4px 0" }}>
+ <Typography.Text strong>Full Access</Typography.Text>
+ <Typography.Paragraph type="secondary" style={{ fontSize: 11, margin: "2px 0 0" }}>
+ Can call all routes (AI APIs, Management, and read-only)
+ </Typography.Paragraph>
+ </div>
+ </Option>
+ </Select>
+ )}
+ </MountedFormField>
+ </div>
+ )}
+
+ {/* Section 3: Optional Settings */}
+ {!isFormDisabled && (
+ <div className="mb-8">
+ <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
+ <h3 className="m-0 text-lg font-medium text-foreground">
+ <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
+ Optional Settings
+ <ChevronDown className={SECTION_CHEVRON_CLASS} />
+ </CollapsibleTrigger>
+ </h3>
+ <CollapsibleContent className="px-4 pb-3">
+ <MountedFormField
+ className="mt-4"
+ label={
+ <span>
+ Max Budget (USD){" "}
+ <Tooltip title="Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
}
- options={guardrailsList.map((name) => ({ value: name, label: name }))}
- />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Disable Global Guardrails{" "}
- <Tooltip title="When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)">
- <a
- href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"
- target="_blank"
- rel="noopener noreferrer"
- onClick={(e) => e.stopPropagation()} // Prevent accordion from collapsing when clicking link
- >
+ name="max_budget"
+ help={`Budget cannot exceed team max budget: $${team?.max_budget !== null && team?.max_budget !== undefined ? team?.max_budget : "unlimited"}`}
+ rules={ceilingRule(
+ team?.max_budget,
+ (limit) => `Budget cannot exceed team max budget: $${formatNumberWithCommas(limit, 4)}`,
+ )}
+ >
+ {(control) => (
+ <NumericalInput
+ {...control}
+ value={control.value as number | string | undefined}
+ step={0.01}
+ precision={2}
+ width={200}
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField
+ className="mt-4"
+ label={
+ <span>
+ Reset Budget{" "}
+ <Tooltip title="How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours">
<InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </a>
- </Tooltip>
- </span>
- }
- name="disable_global_guardrails"
- className="mt-4"
- valuePropName="checked"
- help={
- canEditGuardrails
- ? "Bypass global guardrails for this key"
- : "Premium feature - Upgrade to disable global guardrails by key"
- }
- >
- <Switch disabled={!canEditGuardrails} checkedChildren="Yes" unCheckedChildren="No" />
- </Form.Item>
- {canViewPolicies && (
- <Form.Item
+ </Tooltip>
+ </span>
+ }
+ name="budget_duration"
+ help={`Team Reset Budget: ${team?.budget_duration !== null && team?.budget_duration !== undefined ? team?.budget_duration : "None"}`}
+ >
+ {(control) => (
+ <BudgetDurationDropdown
+ id={control.id}
+ value={control.value as string | null | undefined}
+ showNeverResets
+ placeholder="Not set"
+ onChange={control.onChange}
+ />
+ )}
+ </MountedFormField>
+ <Field className="mt-4">
+ <FieldLabel>
+ <span>
+ Budget Windows{" "}
+ <Tooltip title="Set multiple independent budget windows (e.g., hourly $10 AND monthly $200). Each window tracks spend separately and resets on its own schedule.">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ </FieldLabel>
+ <BudgetWindowsEditor value={budgetLimits} onChange={setBudgetLimits} />
+ </Field>
+ <Field className="mt-4">
+ <FieldLabel>
+ <span>
+ Budget Fallbacks{" "}
+ <Tooltip title="When a model exceeds its per-model budget (model_max_budget), requests automatically reroute to fallback models instead of failing. Configure per-model budgets in Advanced Settings.">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ </FieldLabel>
+ <BudgetFallbacksEditor
+ key={budgetFallbacksKey}
+ value={budgetFallbacks}
+ onChange={setBudgetFallbacks}
+ availableModels={modelsToPick}
+ />
+ </Field>
+ <MountedFormField
+ className="mt-4"
+ label={
+ <span>
+ Tokens per minute Limit (TPM){" "}
+ <Tooltip title="Maximum number of tokens this key can process per minute. Helps control usage and costs">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="tpm_limit"
+ help={`TPM cannot exceed team TPM limit: ${team?.tpm_limit !== null && team?.tpm_limit !== undefined ? team?.tpm_limit : "unlimited"}`}
+ rules={ceilingRule(
+ team?.tpm_limit,
+ (limit) => `TPM limit cannot exceed team TPM limit: ${limit}`,
+ )}
+ >
+ {(control) => (
+ <NumericalInput
+ {...control}
+ value={control.value as number | string | undefined}
+ step={1}
+ width={400}
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField name="tpm_limit_type" bare>
+ {(control) => (
+ <RateLimitTypeFormItem
+ type="tpm"
+ name="tpm_limit_type"
+ className="mt-4"
+ showDetailedDescriptions
+ id={control.id}
+ value={control.value as string | null | undefined}
+ onChange={control.onChange}
+ aria-invalid={control["aria-invalid"] ? true : undefined}
+ aria-describedby={control["aria-describedby"]}
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField
+ className="mt-4"
+ label={
+ <span>
+ Requests per minute Limit (RPM){" "}
+ <Tooltip title="Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="rpm_limit"
+ help={`RPM cannot exceed team RPM limit: ${team?.rpm_limit !== null && team?.rpm_limit !== undefined ? team?.rpm_limit : "unlimited"}`}
+ rules={ceilingRule(
+ team?.rpm_limit,
+ (limit) => `RPM limit cannot exceed team RPM limit: ${limit}`,
+ )}
+ >
+ {(control) => (
+ <NumericalInput
+ {...control}
+ value={control.value as number | string | undefined}
+ step={1}
+ width={400}
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField name="rpm_limit_type" bare>
+ {(control) => (
+ <RateLimitTypeFormItem
+ type="rpm"
+ name="rpm_limit_type"
+ className="mt-4"
+ showDetailedDescriptions
+ id={control.id}
+ value={control.value as string | null | undefined}
+ onChange={control.onChange}
+ aria-invalid={control["aria-invalid"] ? true : undefined}
+ aria-describedby={control["aria-describedby"]}
+ />
+ )}
+ </MountedFormField>
+ <Field className="mt-4">
+ <FieldLabel>
+ <span>
+ Per-Tag Rate Limits{" "}
+ <Tooltip title="Scope rate limits to a request tag so each tag (e.g. a cell or group) gets its own RPM counter. Requests without a matching tag fall back to the key-level limit.">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ </FieldLabel>
+ <TagRateLimitEditor value={tagRateLimits} onChange={setTagRateLimits} />
+ </Field>
+ <MountedFormField
+ className="mt-4"
label={
<span>
- Policies{" "}
- <Tooltip title="Apply policies to this key to control guardrails and other settings">
+ Throttle on budget exceeded{" "}
+ <Tooltip title="When this key exceeds its max budget, throttle its TPM/RPM to the globally configured percentage instead of blocking access entirely. Requires budget_exceeded_throttle_percentage in litellm_settings and a TPM/RPM limit on the key.">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="throttle_on_budget_exceeded"
+ >
+ {(control) => (
+ <Switch
+ id={control.id}
+ checked={control.value as boolean | undefined}
+ onChange={control.onChange}
+ checkedChildren="Yes"
+ unCheckedChildren="No"
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField
+ className="mt-4"
+ label={
+ <span>
+ Enable Prompt Caching{" "}
+ <Tooltip title="Automatically add prompt caching breakpoints (cache_control markers) to requests made with this key, cutting input cost on repeated prompts. Applies to Anthropic and Bedrock Claude models; requests that already set their own cache_control markers are left untouched.">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="enable_prompt_caching"
+ >
+ {(control) => (
+ <Switch
+ id={control.id}
+ checked={control.value as boolean | undefined}
+ onChange={control.onChange}
+ checkedChildren="Yes"
+ unCheckedChildren="No"
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField
+ label={
+ <span>
+ Guardrails{" "}
+ <Tooltip title="Apply safety guardrails to this key to filter content or enforce policies">
<a
- href="https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies"
+ href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()} // Prevent accordion from collapsing when clicking link
@@ -1146,33 +1201,37 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
</Tooltip>
</span>
}
- name="policies"
+ name="guardrails"
className="mt-4"
help={
- premiumUser
- ? "Select existing policies or enter new ones"
- : "Premium feature - Upgrade to set policies by key"
+ canEditGuardrails
+ ? "Select existing guardrails or enter new ones"
+ : "Premium feature - Upgrade to set guardrails by key"
}
>
- <Select
- mode="tags"
- style={{ width: "100%" }}
- disabled={!premiumUser}
- placeholder={
- !premiumUser ? "Premium feature - Upgrade to set policies by key" : "Select or enter policies"
- }
- options={policiesList.map((name) => ({ value: name, label: name }))}
- />
- </Form.Item>
- )}
- {canViewPrompts && (
- <Form.Item
+ {(control) => (
+ <Select
+ {...control}
+ value={control.value as string[] | undefined}
+ mode="tags"
+ style={{ width: "100%" }}
+ disabled={!canEditGuardrails}
+ placeholder={
+ !canEditGuardrails
+ ? "Premium feature - Upgrade to set guardrails by key"
+ : "Select or enter guardrails"
+ }
+ options={guardrailsList.map((name) => ({ value: name, label: name }))}
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField
label={
<span>
- Prompts{" "}
- <Tooltip title="Allow this key to use specific prompt templates">
+ Disable Global Guardrails{" "}
+ <Tooltip title="When enabled, this key will bypass any guardrails configured to run on every request (global guardrails)">
<a
- href="https://docs.litellm.ai/docs/proxy/prompt_management"
+ href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()} // Prevent accordion from collapsing when clicking link
@@ -1182,395 +1241,497 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
</Tooltip>
</span>
}
- name="prompts"
+ name="disable_global_guardrails"
className="mt-4"
help={
- premiumUser
- ? "Select existing prompts or enter new ones"
- : "Premium feature - Upgrade to set prompts by key"
+ canEditGuardrails
+ ? "Bypass global guardrails for this key"
+ : "Premium feature - Upgrade to disable global guardrails by key"
}
>
- <Select
- mode="tags"
- style={{ width: "100%" }}
- disabled={!premiumUser}
- placeholder={
- !premiumUser ? "Premium feature - Upgrade to set prompts by key" : "Select or enter prompts"
- }
- options={promptsList.map((name) => ({ value: name, label: name }))}
- />
- </Form.Item>
- )}
- <Form.Item
- label={
- <span>
- Access Groups{" "}
- <Tooltip title="Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="access_group_ids"
- className="mt-4"
- help="Select access groups to assign to this key"
- >
- <AccessGroupSelector placeholder="Select access groups (optional)" />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Allowed Pass Through Routes{" "}
- <Tooltip title="Allow this key to use specific pass through routes">
- <a
- href="https://docs.litellm.ai/docs/proxy/pass_through"
- target="_blank"
- rel="noopener noreferrer"
- onClick={(e) => e.stopPropagation()} // Prevent accordion from collapsing when clicking link
- >
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </a>
- </Tooltip>
- </span>
- }
- name="allowed_passthrough_routes"
- className="mt-4"
- help={
- premiumUser
- ? "Select existing pass through routes or enter new ones"
- : "Premium feature - Upgrade to set pass through routes by key"
- }
- >
- <PassThroughRoutesSelector
- accessToken={accessToken}
- placeholder={
- !premiumUser
- ? "Premium feature - Upgrade to set pass through routes by key"
- : "Select or enter pass through routes"
- }
- disabled={!premiumUser}
- teamId={selectedCreateKeyTeam ? selectedCreateKeyTeam.team_id : null}
- />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Allowed Vector Stores{" "}
- <Tooltip title="Select which vector stores this key can access. If none selected, the key will have access to all available vector stores">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="allowed_vector_store_ids"
- className="mt-4"
- help="Select vector stores this key can access. Leave empty for access to all vector stores"
- >
- <VectorStoreSelector
- onChange={(values: string[]) => form.setFieldValue("allowed_vector_store_ids", values)}
- value={form.getFieldValue("allowed_vector_store_ids")}
- accessToken={accessToken}
- placeholder="Select vector stores (optional)"
- />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Metadata{" "}
- <Tooltip title="JSON object with additional information about this key. Used for tracking or custom logic">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="metadata"
- className="mt-4"
- >
- <AntdInput.TextArea rows={4} placeholder="Enter metadata as JSON" />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Tags{" "}
- <Tooltip title="Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
- </Tooltip>
- </span>
- }
- name="tags"
- className="mt-4"
- help={`Tags for tracking spend and/or doing tag-based routing.`}
- >
- <Select
- mode="tags"
- style={{ width: "100%" }}
- placeholder="Select or enter tags"
- tokenSeparators={[","]}
- options={tagOptions}
- />
- </Form.Item>
- <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
- <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
- <b>MCP Settings</b>
- <ChevronDown className={SECTION_CHEVRON_CLASS} />
- </CollapsibleTrigger>
- <CollapsibleContent className="px-4 pb-3">
- <Form.Item
+ {(control) => (
+ <Switch
+ id={control.id}
+ checked={control.value as boolean | undefined}
+ onChange={control.onChange}
+ disabled={!canEditGuardrails}
+ checkedChildren="Yes"
+ unCheckedChildren="No"
+ />
+ )}
+ </MountedFormField>
+ {canViewPolicies && (
+ <MountedFormField
label={
<span>
- Allowed MCP Servers{" "}
- <Tooltip title="Select which MCP servers or access groups this key can access">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ Policies{" "}
+ <Tooltip title="Apply policies to this key to control guardrails and other settings">
+ <a
+ href="https://docs.litellm.ai/docs/proxy/guardrails/guardrail_policies"
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={(e) => e.stopPropagation()} // Prevent accordion from collapsing when clicking link
+ >
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </a>
</Tooltip>
</span>
}
- name="allowed_mcp_servers_and_groups"
- help="Select MCP servers or access groups this key can access"
- >
- <MCPServerSelector
- onChange={(val: any) => form.setFieldValue("allowed_mcp_servers_and_groups", val)}
- value={form.getFieldValue("allowed_mcp_servers_and_groups")}
- accessToken={accessToken}
- teamId={selectedCreateKeyTeam?.team_id ?? null}
- placeholder="Select MCP servers or access groups (optional)"
- allowNoMcpServers
- />
- </Form.Item>
-
- {/* Hidden field to register mcp_tool_permissions with the form */}
- <Form.Item name="mcp_tool_permissions" initialValue={{}} hidden>
- <AntdInput type="hidden" />
- </Form.Item>
-
- <Form.Item
- noStyle
- shouldUpdate={(prevValues, currentValues) =>
- prevValues.allowed_mcp_servers_and_groups !== currentValues.allowed_mcp_servers_and_groups ||
- prevValues.mcp_tool_permissions !== currentValues.mcp_tool_permissions
+ name="policies"
+ className="mt-4"
+ help={
+ premiumUser
+ ? "Select existing policies or enter new ones"
+ : "Premium feature - Upgrade to set policies by key"
}
>
- {() => (
- <div className="mt-6">
- <MCPToolPermissions
- accessToken={accessToken}
- selectedServers={(
- form.getFieldValue("allowed_mcp_servers_and_groups")?.servers || []
- ).filter((s: string) => s !== NO_MCP_SERVERS_SENTINEL)}
- toolPermissions={form.getFieldValue("mcp_tool_permissions") || {}}
- onChange={(toolPerms) => form.setFieldsValue({ mcp_tool_permissions: toolPerms })}
- />
- </div>
+ {(control) => (
+ <Select
+ {...control}
+ value={control.value as string[] | undefined}
+ mode="tags"
+ style={{ width: "100%" }}
+ disabled={!premiumUser}
+ placeholder={
+ !premiumUser
+ ? "Premium feature - Upgrade to set policies by key"
+ : "Select or enter policies"
+ }
+ options={policiesList.map((name) => ({ value: name, label: name }))}
+ />
)}
- </Form.Item>
- </CollapsibleContent>
- </Collapsible>
-
- <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
- <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
- <b>Agent Settings</b>
- <ChevronDown className={SECTION_CHEVRON_CLASS} />
- </CollapsibleTrigger>
- <CollapsibleContent className="px-4 pb-3">
- <Form.Item
+ </MountedFormField>
+ )}
+ {canViewPrompts && (
+ <MountedFormField
label={
<span>
- Allowed Agents{" "}
- <Tooltip title="Select which agents or access groups this key can access">
- <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ Prompts{" "}
+ <Tooltip title="Allow this key to use specific prompt templates">
+ <a
+ href="https://docs.litellm.ai/docs/proxy/prompt_management"
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={(e) => e.stopPropagation()} // Prevent accordion from collapsing when clicking link
+ >
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </a>
</Tooltip>
</span>
}
- name="allowed_agents_and_groups"
- help="Select agents or access groups this key can access"
+ name="prompts"
+ className="mt-4"
+ help={
+ premiumUser
+ ? "Select existing prompts or enter new ones"
+ : "Premium feature - Upgrade to set prompts by key"
+ }
>
- <AgentSelector
- onChange={(val: any) => form.setFieldValue("allowed_agents_and_groups", val)}
- value={form.getFieldValue("allowed_agents_and_groups")}
+ {(control) => (
+ <Select
+ {...control}
+ value={control.value as string[] | undefined}
+ mode="tags"
+ style={{ width: "100%" }}
+ disabled={!premiumUser}
+ placeholder={
+ !premiumUser
+ ? "Premium feature - Upgrade to set prompts by key"
+ : "Select or enter prompts"
+ }
+ options={promptsList.map((name) => ({ value: name, label: name }))}
+ />
+ )}
+ </MountedFormField>
+ )}
+ <MountedFormField
+ label={
+ <span>
+ Access Groups{" "}
+ <Tooltip title="Assign access groups to this key. Access groups control which models, MCP servers, and agents this key can use">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="access_group_ids"
+ className="mt-4"
+ help="Select access groups to assign to this key"
+ >
+ {(control) => (
+ <AccessGroupSelector
+ value={control.value as string[] | undefined}
+ onChange={control.onChange}
+ placeholder="Select access groups (optional)"
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField
+ label={
+ <span>
+ Allowed Pass Through Routes{" "}
+ <Tooltip title="Allow this key to use specific pass through routes">
+ <a
+ href="https://docs.litellm.ai/docs/proxy/pass_through"
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={(e) => e.stopPropagation()} // Prevent accordion from collapsing when clicking link
+ >
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </a>
+ </Tooltip>
+ </span>
+ }
+ name="allowed_passthrough_routes"
+ className="mt-4"
+ help={
+ premiumUser
+ ? "Select existing pass through routes or enter new ones"
+ : "Premium feature - Upgrade to set pass through routes by key"
+ }
+ >
+ {(control) => (
+ <PassThroughRoutesSelector
+ value={control.value as string[] | undefined}
+ onChange={control.onChange}
accessToken={accessToken}
- placeholder="Select agents or access groups (optional)"
+ placeholder={
+ !premiumUser
+ ? "Premium feature - Upgrade to set pass through routes by key"
+ : "Select or enter pass through routes"
+ }
+ disabled={!premiumUser}
+ teamId={selectedCreateKeyTeam ? selectedCreateKeyTeam.team_id : null}
/>
- </Form.Item>
- </CollapsibleContent>
- </Collapsible>
-
- {premiumUser ? (
+ )}
+ </MountedFormField>
+ <MountedFormField
+ label={
+ <span>
+ Allowed Vector Stores{" "}
+ <Tooltip title="Select which vector stores this key can access. If none selected, the key will have access to all available vector stores">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="allowed_vector_store_ids"
+ className="mt-4"
+ help="Select vector stores this key can access. Leave empty for access to all vector stores"
+ >
+ {(control) => (
+ <VectorStoreSelector
+ onChange={control.onChange}
+ value={control.value as string[] | undefined}
+ accessToken={accessToken}
+ placeholder="Select vector stores (optional)"
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField
+ label={
+ <span>
+ Metadata{" "}
+ <Tooltip title="JSON object with additional information about this key. Used for tracking or custom logic">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="metadata"
+ className="mt-4"
+ >
+ {(control) => (
+ <AntdInput.TextArea
+ {...control}
+ value={control.value as string | undefined}
+ rows={4}
+ placeholder="Enter metadata as JSON"
+ />
+ )}
+ </MountedFormField>
+ <MountedFormField
+ label={
+ <span>
+ Tags{" "}
+ <Tooltip title="Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="tags"
+ className="mt-4"
+ help={`Tags for tracking spend and/or doing tag-based routing.`}
+ >
+ {(control) => (
+ <Select
+ {...control}
+ value={control.value as string[] | undefined}
+ mode="tags"
+ style={{ width: "100%" }}
+ placeholder="Select or enter tags"
+ tokenSeparators={[","]}
+ options={tagOptions}
+ />
+ )}
+ </MountedFormField>
<Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
<CollapsibleTrigger className={SECTION_HEADER_CLASS}>
- <b>Logging Settings</b>
+ <b>MCP Settings</b>
<ChevronDown className={SECTION_CHEVRON_CLASS} />
</CollapsibleTrigger>
<CollapsibleContent className="px-4 pb-3">
- <div className="mt-4">
- <PremiumLoggingSettings
- value={loggingSettings}
- onChange={setLoggingSettings}
- premiumUser={true}
- disabledCallbacks={disabledCallbacks}
- onDisabledCallbacksChange={setDisabledCallbacks}
- />
- </div>
- </CollapsibleContent>
- </Collapsible>
- ) : (
- <Tooltip
- title={
- <span>
- Key-level logging settings is an enterprise feature, get in touch -
- <a href="https://www.litellm.ai/enterprise" target="_blank">
- https://www.litellm.ai/enterprise
- </a>
- </span>
- }
- placement="top"
- >
- <div style={{ position: "relative" }}>
- <div style={{ opacity: 0.5 }}>
- <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
- <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
- <b>Logging Settings</b>
- <ChevronDown className={SECTION_CHEVRON_CLASS} />
- </CollapsibleTrigger>
- <CollapsibleContent className="px-4 pb-3">
- <div className="mt-4">
- <PremiumLoggingSettings
- value={loggingSettings}
- onChange={setLoggingSettings}
- premiumUser={false}
- disabledCallbacks={disabledCallbacks}
- onDisabledCallbacksChange={setDisabledCallbacks}
- />
- </div>
- </CollapsibleContent>
- </Collapsible>
- </div>
- <div style={{ position: "absolute", inset: 0, cursor: "not-allowed" }} />
- </div>
- </Tooltip>
- )}
-
- <Collapsible
- key={`router-settings-accordion-${routerSettingsKey}`}
- className="mt-4 mb-4 overflow-hidden rounded-lg border"
- >
- <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
- <b>Router Settings</b>
- <ChevronDown className={SECTION_CHEVRON_CLASS} />
- </CollapsibleTrigger>
- <CollapsibleContent className="px-4 pb-3">
- <div className="mt-4 w-full">
- <RouterSettingsAccordion
- key={routerSettingsKey}
- accessToken={accessToken || ""}
- value={routerSettings || undefined}
- onChange={setRouterSettings}
- modelData={
- userModels.length > 0
- ? { data: userModels.map((model) => ({ model_name: model })) }
- : undefined
+ <MountedFormField
+ label={
+ <span>
+ Allowed MCP Servers{" "}
+ <Tooltip title="Select which MCP servers or access groups this key can access">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
}
- />
- </div>
- </CollapsibleContent>
- </Collapsible>
+ name="allowed_mcp_servers_and_groups"
+ help="Select MCP servers or access groups this key can access"
+ >
+ {(control) => (
+ <MCPServerSelector
+ onChange={control.onChange}
+ value={control.value as McpSelectorValue | undefined}
+ accessToken={accessToken}
+ teamId={selectedCreateKeyTeam?.team_id ?? null}
+ placeholder="Select MCP servers or access groups (optional)"
+ allowNoMcpServers
+ />
+ )}
+ </MountedFormField>
- <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
- <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
- <b>Model Aliases</b>
- <ChevronDown className={SECTION_CHEVRON_CLASS} />
- </CollapsibleTrigger>
- <CollapsibleContent className="px-4 pb-3">
- <div className="mt-4">
- <p className="text-sm text-gray-600 mb-4">
- Create custom aliases for models that can be used in API calls. This allows you to create
- shortcuts for specific models.
- </p>
- <ModelAliasManager
+ {/* Hidden field to register mcp_tool_permissions with the form */}
+ <MountedFormField name="mcp_tool_permissions" bare>
+ {(control) => <input type="hidden" id={control.id} name={control.name} />}
+ </MountedFormField>
+
+ <McpToolPermissionsField
accessToken={accessToken}
- initialModelAliases={modelAliases}
- onAliasUpdate={setModelAliases}
- showExampleConfig={false}
+ control={form.control}
+ setValue={form.setValue}
/>
- </div>
- </CollapsibleContent>
- </Collapsible>
+ </CollapsibleContent>
+ </Collapsible>
- <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
- <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
- <b>Key Lifecycle</b>
- <ChevronDown className={SECTION_CHEVRON_CLASS} />
- </CollapsibleTrigger>
- <CollapsibleContent className="px-4 pb-3">
- <div className="mt-4">
- <Form.Item name="duration" initialValue="" noStyle>
- <KeyLifecycleSettings
- autoRotationEnabled={autoRotationEnabled}
- onAutoRotationChange={setAutoRotationEnabled}
- rotationInterval={rotationInterval}
- onRotationIntervalChange={setRotationInterval}
- isCreateMode={true}
- />
- </Form.Item>
- </div>
- </CollapsibleContent>
- </Collapsible>
- <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
- <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
- <div className="flex items-center gap-2">
- <b>Advanced Settings</b>
- <Tooltip
- title={
+ <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
+ <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
+ <b>Agent Settings</b>
+ <ChevronDown className={SECTION_CHEVRON_CLASS} />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="px-4 pb-3">
+ <MountedFormField
+ label={
<span>
- Learn more about advanced settings in our{" "}
- <a
- href={
- proxyBaseUrl
- ? `${proxyBaseUrl}/#/key%20management/generate_key_fn_key_generate_post`
- : `/#/key%20management/generate_key_fn_key_generate_post`
- }
- target="_blank"
- rel="noopener noreferrer"
- className="text-blue-400 hover:text-blue-300"
- >
- documentation
- </a>
+ Allowed Agents{" "}
+ <Tooltip title="Select which agents or access groups this key can access">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
</span>
}
+ name="allowed_agents_and_groups"
+ help="Select agents or access groups this key can access"
>
- <InfoCircleOutlined className="text-gray-400 hover:text-gray-300 cursor-help" />
- </Tooltip>
- </div>
- <ChevronDown className={SECTION_CHEVRON_CLASS} />
- </CollapsibleTrigger>
- <CollapsibleContent className="px-4 pb-3">
- <SchemaFormFields
- schemaComponent="GenerateKeyRequest"
- form={form}
- excludedFields={[
- "key_alias",
- "team_id",
- "organization_id",
- "models",
- "duration",
- "metadata",
- "tags",
- "guardrails",
- "max_budget",
- "budget_duration",
- "tpm_limit",
- "rpm_limit",
- ...(disableCustomApiKeys ? ["key"] : []),
- ]}
- />
- </CollapsibleContent>
- </Collapsible>
- </CollapsibleContent>
- </Collapsible>
- </div>
- )}
+ {(control) => (
+ <AgentSelector
+ onChange={control.onChange}
+ value={control.value as AgentSelectorValue | undefined}
+ accessToken={accessToken}
+ placeholder="Select agents or access groups (optional)"
+ />
+ )}
+ </MountedFormField>
+ </CollapsibleContent>
+ </Collapsible>
- <div style={{ textAlign: "right", marginTop: "10px" }}>
- <Button2 htmlType="submit" disabled={isFormDisabled} style={{ opacity: isFormDisabled ? 0.5 : 1 }}>
- Create Key
- </Button2>
- </div>
- </Form>
+ {premiumUser ? (
+ <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
+ <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
+ <b>Logging Settings</b>
+ <ChevronDown className={SECTION_CHEVRON_CLASS} />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="px-4 pb-3">
+ <div className="mt-4">
+ <PremiumLoggingSettings
+ value={loggingSettings}
+ onChange={setLoggingSettings}
+ premiumUser={true}
+ disabledCallbacks={disabledCallbacks}
+ onDisabledCallbacksChange={setDisabledCallbacks}
+ />
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ ) : (
+ <Tooltip
+ title={
+ <span>
+ Key-level logging settings is an enterprise feature, get in touch -
+ <a href="https://www.litellm.ai/enterprise" target="_blank">
+ https://www.litellm.ai/enterprise
+ </a>
+ </span>
+ }
+ placement="top"
+ >
+ <div style={{ position: "relative" }}>
+ <div style={{ opacity: 0.5 }}>
+ <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
+ <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
+ <b>Logging Settings</b>
+ <ChevronDown className={SECTION_CHEVRON_CLASS} />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="px-4 pb-3">
+ <div className="mt-4">
+ <PremiumLoggingSettings
+ value={loggingSettings}
+ onChange={setLoggingSettings}
+ premiumUser={false}
+ disabledCallbacks={disabledCallbacks}
+ onDisabledCallbacksChange={setDisabledCallbacks}
+ />
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ <div style={{ position: "absolute", inset: 0, cursor: "not-allowed" }} />
+ </div>
+ </Tooltip>
+ )}
+
+ <Collapsible
+ key={`router-settings-accordion-${routerSettingsKey}`}
+ className="mt-4 mb-4 overflow-hidden rounded-lg border"
+ >
+ <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
+ <b>Router Settings</b>
+ <ChevronDown className={SECTION_CHEVRON_CLASS} />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="px-4 pb-3">
+ <div className="mt-4 w-full">
+ <RouterSettingsAccordion
+ key={routerSettingsKey}
+ accessToken={accessToken || ""}
+ value={routerSettings || undefined}
+ onChange={setRouterSettings}
+ modelData={
+ userModels.length > 0
+ ? { data: userModels.map((model) => ({ model_name: model })) }
+ : undefined
+ }
+ />
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+
+ <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
+ <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
+ <b>Model Aliases</b>
+ <ChevronDown className={SECTION_CHEVRON_CLASS} />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="px-4 pb-3">
+ <div className="mt-4">
+ <p className="text-sm text-muted-foreground mb-4">
+ Create custom aliases for models that can be used in API calls. This allows you to create
+ shortcuts for specific models.
+ </p>
+ <ModelAliasManager
+ accessToken={accessToken}
+ initialModelAliases={modelAliases}
+ onAliasUpdate={setModelAliases}
+ showExampleConfig={false}
+ />
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+
+ <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
+ <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
+ <b>Key Lifecycle</b>
+ <ChevronDown className={SECTION_CHEVRON_CLASS} />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="px-4 pb-3">
+ <div className="mt-4">
+ <MountedFormField name="duration" bare>
+ {(control) => (
+ <KeyLifecycleSettings
+ id={control.id}
+ value={control.value as string | undefined}
+ onChange={control.onChange}
+ autoRotationEnabled={autoRotationEnabled}
+ onAutoRotationChange={setAutoRotationEnabled}
+ rotationInterval={rotationInterval}
+ onRotationIntervalChange={setRotationInterval}
+ isCreateMode={true}
+ />
+ )}
+ </MountedFormField>
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ <Collapsible className="mt-4 mb-4 overflow-hidden rounded-lg border">
+ <CollapsibleTrigger className={SECTION_HEADER_CLASS}>
+ <div className="flex items-center gap-2">
+ <b>Advanced Settings</b>
+ <Tooltip
+ title={
+ <span>
+ Learn more about advanced settings in our{" "}
+ <a
+ href={
+ proxyBaseUrl
+ ? `${proxyBaseUrl}/#/key%20management/generate_key_fn_key_generate_post`
+ : `/#/key%20management/generate_key_fn_key_generate_post`
+ }
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-400 hover:text-blue-300"
+ >
+ documentation
+ </a>
+ </span>
+ }
+ >
+ <InfoCircleOutlined className="text-muted-foreground hover:text-foreground cursor-help" />
+ </Tooltip>
+ </div>
+ <ChevronDown className={SECTION_CHEVRON_CLASS} />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="px-4 pb-3">
+ <SchemaFormFields
+ schemaComponent="GenerateKeyRequest"
+ setValue={form.setValue}
+ excludedFields={[
+ "key_alias",
+ "team_id",
+ "organization_id",
+ "models",
+ "duration",
+ "metadata",
+ "tags",
+ "guardrails",
+ "max_budget",
+ "budget_duration",
+ "tpm_limit",
+ "rpm_limit",
+ ...(disableCustomApiKeys ? ["key"] : []),
+ ]}
+ />
+ </CollapsibleContent>
+ </Collapsible>
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ )}
+
+ <div style={{ textAlign: "right", marginTop: "10px" }}>
+ <Button2 htmlType="submit" disabled={isFormDisabled} style={{ opacity: isFormDisabled ? 0.5 : 1 }}>
+ Create Key
+ </Button2>
+ </div>
+ </form>
+ </MountedFormProvider>
</Modal>
{/* Add the Create User Modal */}
@@ -1595,7 +1756,7 @@ const CreateKey: React.FC<CreateKeyProps> = ({ team, teams, data, addKey, autoOp
{apiKey && (
<Modal open={isModalVisible} onOk={handleOk} onCancel={handleCancel} footer={null}>
<div className="grid grid-cols-1 gap-2 w-full">
- <h3 className="text-lg font-medium text-gray-900">Save your Key</h3>
+ <h3 className="text-lg font-medium text-foreground">Save your Key</h3>
{apiKey != null ? (
<CreatedKeyDisplay apiKey={apiKey} />
) : (