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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Team admin view for add models
yuneng-jiangac798b7c92a5
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsxindex 315b41393d6..4b62ce8cf88 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/models-and-endpoints/ModelsAndEndpointsView.tsx@@ -536,21 +536,19 @@ const ModelsAndEndpointsView: React.FC<ModelDashboardProps> = ({);};- const handleOk = () => {- addModelForm- .validateFields()- .then((values: any) => {- handleAddModelSubmit(values, accessToken, addModelForm, handleRefreshClick);- })- .catch((error: any) => {- const errorMessages =- error.errorFields- ?.map((field: any) => {- return `${field.name.join(".")}: ${field.errors.join(", ")}`;- })- .join(" | ") || "Unknown validation error";- NotificationsManager.fromBackend(`Please fill in the following required fields: ${errorMessages}`);- });+ const handleOk = async () => {+ try {+ const values = await addModelForm.validateFields();+ await handleAddModelSubmit(values, accessToken, addModelForm, handleRefreshClick);+ } catch (error: any) {+ const errorMessages =+ error.errorFields+ ?.map((field: any) => {+ return `${field.name.join(".")}: ${field.errors.join(", ")}`;+ })+ .join(" | ") || "Unknown validation error";+ NotificationsManager.fromBackend(`Please fill in the following required fields: ${errorMessages}`);+ }};Object.keys(Providers).find((key) => (Providers as { [index: string]: any })[key] === selectedProvider);diff --git a/ui/litellm-dashboard/src/components/add_model/AddModelForm.tsx b/ui/litellm-dashboard/src/components/add_model/AddModelForm.tsxindex 7ddc7840464..59ac63cffe6 100644--- a/ui/litellm-dashboard/src/components/add_model/AddModelForm.tsx+++ b/ui/litellm-dashboard/src/components/add_model/AddModelForm.tsx@@ -1,10 +1,10 @@import { useProviderFields } from "@/app/(dashboard)/hooks/providers/useProviderFields";import { useGuardrails } from "@/app/(dashboard)/hooks/guardrails/useGuardrails";import { useTags } from "@/app/(dashboard)/hooks/tags/useTags";-import { all_admin_roles } from "@/utils/roles";+import { all_admin_roles, isUserTeamAdminForAnyTeam } from "@/utils/roles";import { Switch, Text } from "@tremor/react";import type { FormInstance } from "antd";-import { Select as AntdSelect, Button, Card, Col, Form, Modal, Row, Tooltip, Typography } from "antd";+import { Select as AntdSelect, Button, Card, Col, Form, Modal, Row, Tooltip, Typography, Alert } from "antd";import type { UploadProps } from "antd/es/upload";import React, { useEffect, useMemo, useState } from "react";import TeamDropdown from "../common_components/team_dropdown";@@ -22,7 +22,7 @@ import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";interface AddModelFormProps {form: FormInstance; // For the Add Model tab- handleOk: () => void;+ handleOk: () => Promise<void>;selectedProvider: Providers;setSelectedProvider: (provider: Providers) => void;providerModels: string[];@@ -57,7 +57,7 @@ const AddModelForm: React.FC<AddModelFormProps> = ({// Using a unique ID to force the ConnectionErrorDisplay to remount and run a fresh testconst [connectionTestId, setConnectionTestId] = useState<string>("");- const { accessToken, userRole, premiumUser } = useAuthorized();+ const { accessToken, userRole, premiumUser, userId } = useAuthorized();const {data: providerMetadata,isLoading: isProviderMetadataLoading,@@ -73,8 +73,9 @@ const AddModelForm: React.FC<AddModelFormProps> = ({};const [isTeamOnly, setIsTeamOnly] = useState<boolean>(false);-const [modelAccessGroups, setModelAccessGroups] = useState<string[]>([]);+ // Team admin specific state+ const [teamAdminSelectedTeam, setTeamAdminSelectedTeam] = useState<string | null>(null);useEffect(() => {const fetchModelAccessGroups = async () => {@@ -98,16 +99,20 @@ const AddModelForm: React.FC<AddModelFormProps> = ({: null;const isAdmin = all_admin_roles.includes(userRole);+ const isTeamAdmin = isUserTeamAdminForAnyTeam(teams, userId);return (<><Title level={2}>Add Model</Title>+<Card><Formform={form}- onFinish={(values) => {+ onFinish={async (values) => {console.log("🔥 Form onFinish triggered with values:", values);- handleOk();+ await handleOk().then(() => {+ setTeamAdminSelectedTeam(null);+ });}}onFinishFailed={(errorInfo) => {console.log("💥 Form onFinishFailed triggered:", errorInfo);@@ -117,215 +122,245 @@ const AddModelForm: React.FC<AddModelFormProps> = ({labelAlign="left"><>- {/* Provider Selection */}- <Form.Item- rules={[{ required: true, message: "Required" }]}- label="Provider:"- name="custom_llm_provider"- tooltip="E.g. OpenAI, Azure OpenAI, Anthropic, Bedrock, etc."- labelCol={{ span: 10 }}- labelAlign="left"- >- <AntdSelect- virtual={false}- showSearch- loading={isProviderMetadataLoading}- placeholder={isProviderMetadataLoading ? "Loading providers..." : "Select a provider"}- optionFilterProp="data-label"- onChange={(value) => {- setSelectedProvider(value as Providers);- setProviderModelsFn(value as Providers);- form.setFieldsValue({- custom_llm_provider: value,- });- form.setFieldsValue({- model: [],- model_name: undefined,- });- }}- >- {providerMetadataErrorText && sortedProviderMetadata.length === 0 && (- <AntdSelect.Option key="__error" value="">- {providerMetadataErrorText}- </AntdSelect.Option>+ {isTeamAdmin && !isAdmin && (+ <>+ <Form.Item+ label="Select Team"+ name="team_id"+ rules={[{ required: true, message: "Please select a team to continue" }]}+ tooltip="Select the team for which you want to add this model"+ >+ <TeamDropdown+ teams={teams}+ onChange={(value) => {+ setTeamAdminSelectedTeam(value);+ }}+ />+ </Form.Item>+ {!teamAdminSelectedTeam && (+ <Alert+ message="Team Selection Required"+ description="As a team admin, you need to select your team first before adding models."+ type="info"+ showIcon+ className="mb-4"+ />)}- {sortedProviderMetadata.map((providerInfo) => {- const displayName = providerInfo.provider_display_name;- const providerKey = providerInfo.provider;- const logoSrc = providerLogoMap[displayName] ?? "";-- return (- <AntdSelect.Option key={providerKey} value={providerKey} data-label={displayName}>- <div className="flex items-center space-x-2">- <ProviderLogo provider={providerKey} className="w-5 h-5" />- <span>{displayName}</span>- </div>- </AntdSelect.Option>- );- })}- </AntdSelect>- </Form.Item>- <LiteLLMModelNameField- selectedProvider={selectedProvider}- providerModels={providerModels}- getPlaceholder={getPlaceholder}- />-- {/* Conditionally Render "Public Model Name" */}- <ConditionalPublicModelName />+ </>+ )}+ {(isAdmin || (isTeamAdmin && teamAdminSelectedTeam)) && (+ <>+ <Form.Item+ rules={[{ required: true, message: "Required" }]}+ label="Provider:"+ name="custom_llm_provider"+ tooltip="E.g. OpenAI, Azure OpenAI, Anthropic, Bedrock, etc."+ labelCol={{ span: 10 }}+ labelAlign="left"+ >+ <AntdSelect+ virtual={false}+ showSearch+ loading={isProviderMetadataLoading}+ placeholder={isProviderMetadataLoading ? "Loading providers..." : "Select a provider"}+ optionFilterProp="data-label"+ onChange={(value) => {+ setSelectedProvider(value as Providers);+ setProviderModelsFn(value as Providers);+ form.setFieldsValue({+ custom_llm_provider: value,+ });+ form.setFieldsValue({+ model: [],+ model_name: undefined,+ });+ }}+ >+ {providerMetadataErrorText && sortedProviderMetadata.length === 0 && (+ <AntdSelect.Option key="__error" value="">+ {providerMetadataErrorText}+ </AntdSelect.Option>+ )}+ {sortedProviderMetadata.map((providerInfo) => {+ const displayName = providerInfo.provider_display_name;+ const providerKey = providerInfo.provider;+ const logoSrc = providerLogoMap[displayName] ?? "";- {/* Select Mode */}- <Form.Item label="Mode" name="mode" className="mb-1">- <AntdSelect- style={{ width: "100%" }}- value={testMode}- onChange={(value) => setTestMode(value)}- options={TEST_MODES}- />- </Form.Item>- <Row>- <Col span={10}></Col>- <Col span={10}>- <Text className="mb-5 mt-1">- <strong>Optional</strong> - LiteLLM endpoint to use when health checking this model{" "}- <Link href="https://docs.litellm.ai/docs/proxy/health#health" target="_blank">- Learn more- </Link>- </Text>- </Col>- </Row>+ return (+ <AntdSelect.Option key={providerKey} value={providerKey} data-label={displayName}>+ <div className="flex items-center space-x-2">+ <ProviderLogo provider={providerKey} className="w-5 h-5" />+ <span>{displayName}</span>+ </div>+ </AntdSelect.Option>+ );+ })}+ </AntdSelect>+ </Form.Item>+ <LiteLLMModelNameField+ selectedProvider={selectedProvider}+ providerModels={providerModels}+ getPlaceholder={getPlaceholder}+ />- {/* Credentials */}- <div className="mb-4">- <Typography.Text className="text-sm text-gray-500 mb-2">- Either select existing credentials OR enter new provider credentials below- </Typography.Text>- </div>+ {/* Conditionally Render "Public Model Name" */}+ <ConditionalPublicModelName />- <Form.Item label="Existing Credentials" name="litellm_credential_name" initialValue={null}>- <AntdSelect- showSearch- placeholder="Select or search for existing credentials"- optionFilterProp="children"- filterOption={(input, option) => (option?.label ?? "").toLowerCase().includes(input.toLowerCase())}- options={[- { value: null, label: "None" },- ...credentials.map((credential) => ({- value: credential.credential_name,- label: credential.credential_name,- })),- ]}- allowClear- />- </Form.Item>+ {/* Select Mode */}+ <Form.Item label="Mode" name="mode" className="mb-1">+ <AntdSelect+ style={{ width: "100%" }}+ value={testMode}+ onChange={(value) => setTestMode(value)}+ options={TEST_MODES}+ />+ </Form.Item>+ <Row>+ <Col span={10}></Col>+ <Col span={10}>+ <Text className="mb-5 mt-1">+ <strong>Optional</strong> - LiteLLM endpoint to use when health checking this model{" "}+ <Link href="https://docs.litellm.ai/docs/proxy/health#health" target="_blank">+ Learn more+ </Link>+ </Text>+ </Col>+ </Row>- <Form.Item- noStyle- shouldUpdate={(prevValues, currentValues) =>- prevValues.litellm_credential_name !== currentValues.litellm_credential_name ||- prevValues.provider !== currentValues.provider- }- >- {({ getFieldValue }) => {- const credentialName = getFieldValue("litellm_credential_name");- console.log("🔑 Credential Name Changed:", credentialName);- // Only show provider specific fields if no credentials selected- if (!credentialName) {- return (- <>- <div className="flex items-center my-4">- <div className="flex-grow border-t border-gray-200"></div>- <span className="px-4 text-gray-500 text-sm">OR</span>- <div className="flex-grow border-t border-gray-200"></div>- </div>- <ProviderSpecificFields selectedProvider={selectedProvider} uploadProps={uploadProps} />- </>- );- }- return null;- }}- </Form.Item>- <div className="flex items-center my-4">- <div className="flex-grow border-t border-gray-200"></div>- <span className="px-4 text-gray-500 text-sm">Additional Model Info Settings</span>- <div className="flex-grow border-t border-gray-200"></div>- </div>- {/* Team-only Model Switch */}- <Form.Item- label="Team-BYOK Model"- tooltip="Only use this model + credential combination for this team. Useful when teams want to onboard their own OpenAI keys."- className="mb-4"- >- <Tooltip- title={- !premiumUser- ? "This is an enterprise-only feature. Upgrade to premium to restrict model+credential combinations to a specific team."- : ""- }- placement="top"- >- <Switch- checked={isTeamOnly}- onChange={(checked) => {- setIsTeamOnly(checked);- if (!checked) {- form.setFieldValue("team_id", undefined);- }- }}- disabled={!premiumUser}- />- </Tooltip>- </Form.Item>+ {/* Credentials */}+ <div className="mb-4">+ <Typography.Text className="text-sm text-gray-500 mb-2">+ Either select existing credentials OR enter new provider credentials below+ </Typography.Text>+ </div>- {/* Conditional Team Selection */}- {isTeamOnly && (- <Form.Item- label="Select Team"- name="team_id"- className="mb-4"- tooltip="Only keys for this team will be able to call this model."- rules={[- {- required: isTeamOnly && !isAdmin,- message: "Please select a team.",- },- ]}- >- <TeamDropdown teams={teams} disabled={!premiumUser} />- </Form.Item>- )}- {isAdmin && (- <>- <Form.Item- label="Model Access Group"- name="model_access_group"- className="mb-4"- tooltip="Use model access groups to give users access to select models, and add new ones to the group over time."- >+ <Form.Item label="Existing Credentials" name="litellm_credential_name" initialValue={null}><AntdSelect- mode="tags"showSearch- placeholder="Select existing groups or type to create new ones"+ placeholder="Select or search for existing credentials"optionFilterProp="children"- tokenSeparators={[","]}- options={modelAccessGroups.map((group) => ({- value: group,- label: group,- }))}- maxTagCount="responsive"+ filterOption={(input, option) => (option?.label ?? "").toLowerCase().includes(input.toLowerCase())}+ options={[+ { value: null, label: "None" },+ ...credentials.map((credential) => ({+ value: credential.credential_name,+ label: credential.credential_name,+ })),+ ]}allowClear/></Form.Item>++ <Form.Item+ noStyle+ shouldUpdate={(prevValues, currentValues) =>+ prevValues.litellm_credential_name !== currentValues.litellm_credential_name ||+ prevValues.provider !== currentValues.provider+ }+ >+ {({ getFieldValue }) => {+ const credentialName = getFieldValue("litellm_credential_name");+ console.log("🔑 Credential Name Changed:", credentialName);+ // Only show provider specific fields if no credentials selected+ if (!credentialName) {+ return (+ <>+ <div className="flex items-center my-4">+ <div className="flex-grow border-t border-gray-200"></div>+ <span className="px-4 text-gray-500 text-sm">OR</span>+ <div className="flex-grow border-t border-gray-200"></div>+ </div>+ <ProviderSpecificFields selectedProvider={selectedProvider} uploadProps={uploadProps} />+ </>+ );+ }+ return null;+ }}+ </Form.Item>+ <div className="flex items-center my-4">+ <div className="flex-grow border-t border-gray-200"></div>+ <span className="px-4 text-gray-500 text-sm">Additional Model Info Settings</span>+ <div className="flex-grow border-t border-gray-200"></div>+ </div>+ {/* Team-only Model Switch - Only show for proxy admins, not team admins */}+ {(isAdmin || !isTeamAdmin) && (+ <Form.Item+ label="Team-BYOK Model"+ tooltip="Only use this model + credential combination for this team. Useful when teams want to onboard their own OpenAI keys."+ className="mb-4"+ >+ <Tooltip+ title={+ !premiumUser+ ? "This is an enterprise-only feature. Upgrade to premium to restrict model+credential combinations to a specific team."+ : ""+ }+ placement="top"+ >+ <Switch+ checked={isTeamOnly}+ onChange={(checked) => {+ setIsTeamOnly(checked);+ if (!checked) {+ form.setFieldValue("team_id", undefined);+ }+ }}+ disabled={!premiumUser}+ />+ </Tooltip>+ </Form.Item>+ )}++ {/* Conditional Team Selection */}+ {isTeamOnly && (isAdmin || !isTeamAdmin) && (+ <Form.Item+ label="Select Team"+ name="team_id"+ className="mb-4"+ tooltip="Only keys for this team will be able to call this model."+ rules={[+ {+ required: isTeamOnly && !isAdmin,+ message: "Please select a team.",+ },+ ]}+ >+ <TeamDropdown teams={teams} disabled={!premiumUser} />+ </Form.Item>+ )}+ {isAdmin && (+ <>+ <Form.Item+ label="Model Access Group"+ name="model_access_group"+ className="mb-4"+ tooltip="Use model access groups to give users access to select models, and add new ones to the group over time."+ >+ <AntdSelect+ mode="tags"+ showSearch+ placeholder="Select existing groups or type to create new ones"+ optionFilterProp="children"+ tokenSeparators={[","]}+ options={modelAccessGroups.map((group) => ({+ value: group,+ label: group,+ }))}+ maxTagCount="responsive"+ allowClear+ />+ </Form.Item>+ </>+ )}+ <AdvancedSettings+ showAdvancedSettings={showAdvancedSettings}+ setShowAdvancedSettings={setShowAdvancedSettings}+ teams={teams}+ guardrailsList={guardrailsList || []}+ tagsList={tagsList || {}}+ /></>)}- <AdvancedSettings- showAdvancedSettings={showAdvancedSettings}- setShowAdvancedSettings={setShowAdvancedSettings}- teams={teams}- guardrailsList={guardrailsList || []}- tagsList={tagsList || {}}- />-<div className="flex justify-between items-center mb-4"><Tooltip title="Get help on our github"><Typography.Link href="https://github.com/BerriAI/litellm/issues">Need Help?</Typography.Link>diff --git a/ui/litellm-dashboard/src/components/add_model/add_model_tab.test.tsx b/ui/litellm-dashboard/src/components/add_model/add_model_tab.test.tsxindex 9362cbb3260..197bcd6569f 100644--- a/ui/litellm-dashboard/src/components/add_model/add_model_tab.test.tsx+++ b/ui/litellm-dashboard/src/components/add_model/add_model_tab.test.tsx@@ -62,6 +62,14 @@ vi.mock("@/app/(dashboard)/hooks/providers/useProviderFields", () => ({}),}));+vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({+ default: vi.fn().mockReturnValue({+ accessToken: "test-access-token",+ userRole: "Admin",+ premiumUser: true,+ }),+}));+const createQueryClient = () =>new QueryClient({defaultOptions: {@@ -137,7 +145,6 @@ const createTestProps = () => {uploadProps,accessToken: "test-access-token",userRole: "Admin",- premiumUser: true,};};@@ -163,7 +170,6 @@ describe("Add Model Tab", () => {credentials={props.credentials}accessToken={props.accessToken}userRole={props.userRole}- premiumUser={props.premiumUser}/></QueryClientProvider>,);@@ -192,7 +198,6 @@ describe("Add Model Tab", () => {credentials={props.credentials}accessToken={props.accessToken}userRole={props.userRole}- premiumUser={props.premiumUser}/></QueryClientProvider>,);@@ -222,7 +227,6 @@ describe("Add Model Tab", () => {credentials={props.credentials}accessToken={props.accessToken}userRole={props.userRole}- premiumUser={props.premiumUser}/></QueryClientProvider>,);@@ -251,7 +255,6 @@ describe("Add Model Tab", () => {credentials={props.credentials}accessToken={props.accessToken}userRole={props.userRole}- premiumUser={props.premiumUser}/></QueryClientProvider>,);@@ -289,7 +292,6 @@ describe("Add Model Tab", () => {credentials={props.credentials}accessToken={props.accessToken}userRole={props.userRole}- premiumUser={props.premiumUser}/></QueryClientProvider>,);diff --git a/ui/litellm-dashboard/src/components/add_model/add_model_tab.tsx b/ui/litellm-dashboard/src/components/add_model/add_model_tab.tsxindex 17ec1cbceee..f9b6533ac60 100644--- a/ui/litellm-dashboard/src/components/add_model/add_model_tab.tsx+++ b/ui/litellm-dashboard/src/components/add_model/add_model_tab.tsx@@ -8,12 +8,11 @@ import { type CredentialItem } from "../networking";import { Providers } from "../provider_info_helpers";import AddAutoRouterTab from "./add_auto_router_tab";import AddModelForm from "./AddModelForm";-import AdvancedSettings from "./advanced_settings";import { handleAddAutoRouterSubmit } from "./handle_add_auto_router_submit";interface AddModelTabProps {form: FormInstance; // For the Add Model tab- handleOk: (values?: any) => void;+ handleOk: (values?: any) => Promise<void>;selectedProvider: Providers;setSelectedProvider: (provider: Providers) => void;providerModels: string[];diff --git a/ui/litellm-dashboard/src/components/templates/model_dashboard.tsx b/ui/litellm-dashboard/src/components/templates/model_dashboard.tsxindex 9dbe04bffb1..d0db4204807 100644--- a/ui/litellm-dashboard/src/components/templates/model_dashboard.tsx+++ b/ui/litellm-dashboard/src/components/templates/model_dashboard.tsx@@ -950,7 +950,7 @@ const OldModelDashboard: React.FC<ModelDashboardProps> = ({);};- const handleOk = () => {+ const handleOk = async () => {console.log("🚀 handleOk called from model dashboard!");console.log("Current form values:", addModelForm.getFieldsValue());@@ -1354,7 +1354,6 @@ const OldModelDashboard: React.FC<ModelDashboardProps> = ({credentials={credentialsList}accessToken={accessToken}userRole={userRole}- premiumUser={premiumUser}/></TabPanel><TabPanel>