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]

Consistent layout for Create and Back buttons on all the pages (#12542)

tanjiro2faba5f21527
diff --git a/ui/litellm-dashboard/.prettierrc.json b/ui/litellm-dashboard/.prettierrc.json
new file mode 100644
index 00000000000..69cb9796325
--- /dev/null
+++ b/ui/litellm-dashboard/.prettierrc.json
@@ -0,0 +1,7 @@
+{
+ "semi": false,
+ "tabWidth": 2,
+ "printWidth": 120,
+ "trailingComma": "all",
+ "jsxBracketSameLine": false
+}
\ No newline at end of file
diff --git a/ui/litellm-dashboard/src/components/bulk_create_users_button.tsx b/ui/litellm-dashboard/src/components/bulk_create_users_button.tsx
index 2dac677b4b0..f7a892d6466 100644
--- a/ui/litellm-dashboard/src/components/bulk_create_users_button.tsx
+++ b/ui/litellm-dashboard/src/components/bulk_create_users_button.tsx
@@ -1,42 +1,49 @@
-import React, { useState, useEffect } from "react";
-import { Button as TremorButton, Text } from "@tremor/react";
-import { Modal, Table, Upload, message, Alert, Typography } from "antd";
-import { UploadOutlined, DownloadOutlined, WarningOutlined, FileTextOutlined, DeleteOutlined, FileExclamationOutlined } from "@ant-design/icons";
-import { userCreateCall, invitationCreateCall, getProxyUISettings } from "./networking";
-import Papa from "papaparse";
-import { CheckCircleIcon, XCircleIcon, ExclamationIcon } from "@heroicons/react/outline";
-import { CopyToClipboard } from "react-copy-to-clipboard";
-import { InvitationLink } from "./onboarding_link";
+import React, { useState, useEffect } from "react"
+import { Button as TremorButton, Text } from "@tremor/react"
+import { Modal, Table, Upload, message, Alert, Typography } from "antd"
+import {
+ UploadOutlined,
+ DownloadOutlined,
+ WarningOutlined,
+ FileTextOutlined,
+ DeleteOutlined,
+ FileExclamationOutlined,
+} from "@ant-design/icons"
+import { userCreateCall, invitationCreateCall, getProxyUISettings } from "./networking"
+import Papa from "papaparse"
+import { CheckCircleIcon, XCircleIcon, ExclamationIcon } from "@heroicons/react/outline"
+import { CopyToClipboard } from "react-copy-to-clipboard"
+import { InvitationLink } from "./onboarding_link"
interface BulkCreateUsersProps {
- accessToken: string;
- teams: any[] | null;
- possibleUIRoles: null | Record<string, Record<string, string>>;
- onUsersCreated?: () => void;
+ accessToken: string
+ teams: any[] | null
+ possibleUIRoles: null | Record<string, Record<string, string>>
+ onUsersCreated?: () => void
}
interface UserData {
- user_email: string;
- user_role: string;
- teams?: string | string[];
- metadata?: string;
- max_budget?: string | number;
- budget_duration?: string;
- models?: string | string[];
- status?: string;
- error?: string;
- rowNumber?: number;
- isValid?: boolean;
- key?: string;
- invitation_link?: string;
+ user_email: string
+ user_role: string
+ teams?: string | string[]
+ metadata?: string
+ max_budget?: string | number
+ budget_duration?: string
+ models?: string | string[]
+ status?: string
+ error?: string
+ rowNumber?: number
+ isValid?: boolean
+ key?: string
+ invitation_link?: string
}
// Define an interface for the UI settings
interface UISettings {
- PROXY_BASE_URL: string | null;
- PROXY_LOGOUT_URL: string | null;
- DEFAULT_TEAM_DISABLED: boolean;
- SSO_ENABLED: boolean;
+ PROXY_BASE_URL: string | null
+ PROXY_LOGOUT_URL: string | null
+ DEFAULT_TEAM_DISABLED: boolean
+ SSO_ENABLED: boolean
}
const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
@@ -45,389 +52,408 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
possibleUIRoles,
onUsersCreated,
}) => {
- const [isModalVisible, setIsModalVisible] = useState(false);
- const [parsedData, setParsedData] = useState<UserData[]>([]);
- const [isProcessing, setIsProcessing] = useState(false);
- const [parseError, setParseError] = useState<string | null>(null);
- const [csvStructureError, setCsvStructureError] = useState<string | null>(null);
- const [fileError, setFileError] = useState<string | null>(null);
- const [selectedFile, setSelectedFile] = useState<File | null>(null);
- const [uiSettings, setUISettings] = useState<UISettings | null>(null);
- const [baseUrl, setBaseUrl] = useState("http://localhost:4000");
+ const [isModalVisible, setIsModalVisible] = useState(false)
+ const [parsedData, setParsedData] = useState<UserData[]>([])
+ const [isProcessing, setIsProcessing] = useState(false)
+ const [parseError, setParseError] = useState<string | null>(null)
+ const [csvStructureError, setCsvStructureError] = useState<string | null>(null)
+ const [fileError, setFileError] = useState<string | null>(null)
+ const [selectedFile, setSelectedFile] = useState<File | null>(null)
+ const [uiSettings, setUISettings] = useState<UISettings | null>(null)
+ const [baseUrl, setBaseUrl] = useState("http://localhost:4000")
useEffect(() => {
// Get UI settings
const fetchUISettings = async () => {
try {
- const uiSettingsResponse = await getProxyUISettings(accessToken);
- setUISettings(uiSettingsResponse);
+ const uiSettingsResponse = await getProxyUISettings(accessToken)
+ setUISettings(uiSettingsResponse)
} catch (error) {
- console.error("Error fetching UI settings:", error);
+ console.error("Error fetching UI settings:", error)
}
- };
+ }
- fetchUISettings();
+ fetchUISettings()
// Set base URL
- const base = new URL("/", window.location.href);
- setBaseUrl(base.toString());
- }, [accessToken]);
+ const base = new URL("/", window.location.href)
+ setBaseUrl(base.toString())
+ }, [accessToken])
const downloadTemplate = () => {
const template = [
["user_email", "user_role", "teams", "max_budget", "budget_duration", "models"],
["[email protected]", "internal_user", "team-id-1,team-id-2", "100", "30d", "gpt-3.5-turbo,gpt-4"],
- ];
-
- const csv = Papa.unparse(template);
- const blob = new Blob([csv], { type: "text/csv" });
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = "bulk_users_template.csv";
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- window.URL.revokeObjectURL(url);
- };
+ ]
+
+ const csv = Papa.unparse(template)
+ const blob = new Blob([csv], { type: "text/csv" })
+ const url = window.URL.createObjectURL(blob)
+ const a = document.createElement("a")
+ a.href = url
+ a.download = "bulk_users_template.csv"
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ window.URL.revokeObjectURL(url)
+ }
const handleFileUpload = (file: File) => {
// Reset all error states
- setParseError(null);
- setCsvStructureError(null);
- setFileError(null);
-
+ setParseError(null)
+ setCsvStructureError(null)
+ setFileError(null)
+
// Set the selected file - always show the file even if it's invalid
- setSelectedFile(file);
-
+ setSelectedFile(file)
+
// Check file type
- if (file.type !== 'text/csv' && !file.name.endsWith('.csv')) {
- setFileError(`Invalid file type: ${file.name}. Please upload a CSV file (.csv extension).`);
- message.error("Invalid file type. Please upload a CSV file.");
- return false;
+ if (file.type !== "text/csv" && !file.name.endsWith(".csv")) {
+ setFileError(`Invalid file type: ${file.name}. Please upload a CSV file (.csv extension).`)
+ message.error("Invalid file type. Please upload a CSV file.")
+ return false
}
-
+
// Check file size (limit to 5MB)
if (file.size > 5 * 1024 * 1024) {
- setFileError(`File is too large (${(file.size / (1024 * 1024)).toFixed(1)} MB). Please upload a CSV file smaller than 5MB.`);
- return false;
+ setFileError(
+ `File is too large (${(file.size / (1024 * 1024)).toFixed(1)} MB). Please upload a CSV file smaller than 5MB.`,
+ )
+ return false
}
Papa.parse(file, {
complete: (results) => {
// Check if file is empty
if (!results.data || results.data.length === 0) {
- setCsvStructureError("The CSV file appears to be empty. Please upload a file with data.");
- setParsedData([]);
- return;
+ setCsvStructureError("The CSV file appears to be empty. Please upload a file with data.")
+ setParsedData([])
+ return
}
-
+
// Check if there's only header row
if (results.data.length === 1) {
- setCsvStructureError("The CSV file only contains headers but no user data. Please add user data to your CSV.");
- setParsedData([]);
- return;
+ setCsvStructureError("The CSV file only contains headers but no user data. Please add user data to your CSV.")
+ setParsedData([])
+ return
}
-
- const headers = results.data[0] as string[];
-
+
+ const headers = results.data[0] as string[]
+
// Check if headers exist
- if (headers.length === 0 || (headers.length === 1 && headers[0] === '')) {
- setCsvStructureError("The CSV file doesn't contain any column headers. Please make sure your CSV has headers.");
- setParsedData([]);
- return;
+ if (headers.length === 0 || (headers.length === 1 && headers[0] === "")) {
+ setCsvStructureError(
+ "The CSV file doesn't contain any column headers. Please make sure your CSV has headers.",
+ )
+ setParsedData([])
+ return
}
-
- const requiredColumns = ['user_email', 'user_role'];
-
+
+ const requiredColumns = ["user_email", "user_role"]
+
// Check if all required columns are present
- const missingColumns = requiredColumns.filter(col => !headers.includes(col));
+ const missingColumns = requiredColumns.filter((col) => !headers.includes(col))
if (missingColumns.length > 0) {
- setCsvStructureError(`Your CSV is missing these required columns: ${missingColumns.join(', ')}. Please add these columns to your CSV file.`);
- setParsedData([]);
- return;
+ setCsvStructureError(
+ `Your CSV is missing these required columns: ${missingColumns.join(", ")}. Please add these columns to your CSV file.`,
+ )
+ setParsedData([])
+ return
}
try {
- const userData = results.data.slice(1).map((row: any, index: number) => {
- // Skip empty rows
- if (row.length === 0 || (row.length === 1 && row[0] === '')) {
- return null;
- }
-
- // Check if row has enough columns
- if (row.length < headers.length) {
- return {
+ const userData = results.data
+ .slice(1)
+ .map((row: any, index: number) => {
+ // Skip empty rows
+ if (row.length === 0 || (row.length === 1 && row[0] === "")) {
+ return null
+ }
+
+ // Check if row has enough columns
+ if (row.length < headers.length) {
+ return {
+ rowNumber: index + 2,
+ isValid: false,
+ error: `Row ${index + 2} has fewer columns than the header row. Please ensure all data is properly formatted.`,
+ user_email: "",
+ user_role: "",
+ } as UserData
+ }
+
+ const user: UserData = {
+ user_email: row[headers.indexOf("user_email")]?.trim() || "",
+ user_role: row[headers.indexOf("user_role")]?.trim() || "",
+ teams: row[headers.indexOf("teams")]?.trim(),
+ max_budget: row[headers.indexOf("max_budget")]?.trim(),
+ budget_duration: row[headers.indexOf("budget_duration")]?.trim(),
+ models: row[headers.indexOf("models")]?.trim(),
rowNumber: index + 2,
- isValid: false,
- error: `Row ${index + 2} has fewer columns than the header row. Please ensure all data is properly formatted.`,
- user_email: '',
- user_role: ''
- } as UserData;
- }
-
- const user: UserData = {
- user_email: row[headers.indexOf("user_email")]?.trim() || '',
- user_role: row[headers.indexOf("user_role")]?.trim() || '',
- teams: row[headers.indexOf("teams")]?.trim(),
- max_budget: row[headers.indexOf("max_budget")]?.trim(),
- budget_duration: row[headers.indexOf("budget_duration")]?.trim(),
- models: row[headers.indexOf("models")]?.trim(),
- rowNumber: index + 2,
- isValid: true,
- error: '',
- };
-
- // Validate the row
- const errors: string[] = [];
-
- // Email validation
- if (!user.user_email) {
- errors.push('Email is required');
- } else if (!user.user_email.includes('@') || !user.user_email.includes('.')) {
- errors.push('Invalid email format (must contain @ and domain)');
- }
-
- // Role validation
- if (!user.user_role) {
- errors.push('Role is required');
- } else {
- // Validate user role
- const validRoles = ['proxy_admin', 'proxy_admin_view_only', 'internal_user', 'internal_user_view_only'];
- if (!validRoles.includes(user.user_role)) {
- errors.push(`Invalid role "${user.user_role}". Must be one of: ${validRoles.join(', ')}`);
+ isValid: true,
+ error: "",
}
- }
-
- // Budget validation
- if (user.max_budget && user.max_budget.toString().trim() !== '') {
- if (isNaN(parseFloat(user.max_budget.toString()))) {
- errors.push(`Max budget "${user.max_budget}" must be a number`);
- } else if (parseFloat(user.max_budget.toString()) <= 0) {
- errors.push('Max budget must be greater than 0');
+
+ // Validate the row
+ const errors: string[] = []
+
+ // Email validation
+ if (!user.user_email) {
+ errors.push("Email is required")
+ } else if (!user.user_email.includes("@") || !user.user_email.includes(".")) {
+ errors.push("Invalid email format (must contain @ and domain)")
}
- }
-
- // Budget duration validation
- if (user.budget_duration && !user.budget_duration.match(/^\d+[dhmwy]$|^\d+mo$/)) {
- errors.push(`Invalid budget duration format "${user.budget_duration}". Use format like "30d", "1mo", "2w", "6h"`);
- }
-
- // Teams validation
- if (user.teams && typeof user.teams === 'string') {
- // Check if teams exist (if teams data is available)
- if (teams && teams.length > 0) {
- const teamIds = teams.map(t => t.team_id);
- const userTeams = user.teams.split(',').map(t => t.trim());
- const invalidTeams = userTeams.filter(t => !teamIds.includes(t));
- if (invalidTeams.length > 0) {
- errors.push(`Unknown team(s): ${invalidTeams.join(', ')}`);
+
+ // Role validation
+ if (!user.user_role) {
+ errors.push("Role is required")
+ } else {
+ // Validate user role
+ const validRoles = ["proxy_admin", "proxy_admin_view_only", "internal_user", "internal_user_view_only"]
+ if (!validRoles.includes(user.user_role)) {
+ errors.push(`Invalid role "${user.user_role}". Must be one of: ${validRoles.join(", ")}`)
}
}
- }
- if (errors.length > 0) {
- user.isValid = false;
- user.error = errors.join(', ');
- }
+ // Budget validation
+ if (user.max_budget && user.max_budget.toString().trim() !== "") {
+ if (isNaN(parseFloat(user.max_budget.toString()))) {
+ errors.push(`Max budget "${user.max_budget}" must be a number`)
+ } else if (parseFloat(user.max_budget.toString()) <= 0) {
+ errors.push("Max budget must be greater than 0")
+ }
+ }
+
+ // Budget duration validation
+ if (user.budget_duration && !user.budget_duration.match(/^\d+[dhmwy]$|^\d+mo$/)) {
+ errors.push(
+ `Invalid budget duration format "${user.budget_duration}". Use format like "30d", "1mo", "2w", "6h"`,
+ )
+ }
- return user;
- }).filter(Boolean) as UserData[]; // Filter out null values (empty rows)
+ // Teams validation
+ if (user.teams && typeof user.teams === "string") {
+ // Check if teams exist (if teams data is available)
+ if (teams && teams.length > 0) {
+ const teamIds = teams.map((t) => t.team_id)
+ const userTeams = user.teams.split(",").map((t) => t.trim())
+ const invalidTeams = userTeams.filter((t) => !teamIds.includes(t))
+ if (invalidTeams.length > 0) {
+ errors.push(`Unknown team(s): ${invalidTeams.join(", ")}`)
+ }
+ }
+ }
+
+ if (errors.length > 0) {
+ user.isValid = false
+ user.error = errors.join(", ")
+ }
+
+ return user
+ })
+ .filter(Boolean) as UserData[] // Filter out null values (empty rows)
- const validData = userData.filter(user => user.isValid);
- setParsedData(userData);
+ const validData = userData.filter((user) => user.isValid)
+ setParsedData(userData)
if (userData.length === 0) {
- setCsvStructureError("No valid data rows found in the CSV file. Please check your file format.");
+ setCsvStructureError("No valid data rows found in the CSV file. Please check your file format.")
} else if (validData.length === 0) {
- setParseError('No valid users found in the CSV. Please check the errors below and fix your CSV file.');
+ setParseError("No valid users found in the CSV. Please check the errors below and fix your CSV file.")
} else if (validData.length < userData.length) {
- setParseError(`Found ${userData.length - validData.length} row(s) with errors out of ${userData.length} total rows. Please correct them before proceeding.`);
+ setParseError(
+ `Found ${userData.length - validData.length} row(s) with errors out of ${userData.length} total rows. Please correct them before proceeding.`,
+ )
} else {
- message.success(`Successfully parsed ${validData.length} users`);
+ message.success(`Successfully parsed ${validData.length} users`)
}
} catch (error: unknown) {
- const errorMessage = error instanceof Error ? error.message : 'Unknown error';
- setParseError(`Error parsing CSV: ${errorMessage}`);
- setParsedData([]);
+ const errorMessage = error instanceof Error ? error.message : "Unknown error"
+ setParseError(`Error parsing CSV: ${errorMessage}`)
+ setParsedData([])
}
},
error: (error) => {
- setParseError(`Failed to parse CSV file: ${error.message}`);
- setParsedData([]);
+ setParseError(`Failed to parse CSV file: ${error.message}`)
+ setParsedData([])
},
header: false,
- });
- return false;
- };
+ })
+ return false
+ }
const removeSelectedFile = () => {
- setSelectedFile(null);
- setParsedData([]);
- setParseError(null);
- setCsvStructureError(null);
- setFileError(null);
- };
+ setSelectedFile(null)
+ setParsedData([])
+ setParseError(null)
+ setCsvStructureError(null)
+ setFileError(null)
+ }
const handleBulkCreate = async () => {
- setIsProcessing(true);
- const updatedData = parsedData.map(user => ({ ...user, status: 'pending' }));
- setParsedData(updatedData);
-
- let anySuccessful = false;
+ setIsProcessing(true)
+ const updatedData = parsedData.map((user) => ({ ...user, status: "pending" }))
+ setParsedData(updatedData)
+
+ let anySuccessful = false
for (let index = 0; index < updatedData.length; index++) {
- const user = updatedData[index];
+ const user = updatedData[index]
try {
// Create a clean user object with only non-empty values
const cleanUser: Partial<UserData> = {
user_email: user.user_email,
- user_role: user.user_role
- };
-
+ user_role: user.user_role,
+ }
+
// Only add optional fields if they have values
- if (user.teams && typeof user.teams === 'string' && user.teams.trim() !== '') {
- cleanUser.teams = user.teams.split(',').map(team => team.trim()).filter(Boolean);
+ if (user.teams && typeof user.teams === "string" && user.teams.trim() !== "") {
+ cleanUser.teams = user.teams
+ .split(",")
+ .map((team) => team.trim())
+ .filter(Boolean)
// Only include teams if there's at least one valid team
if (cleanUser.teams.length === 0) {
- delete cleanUser.teams;
+ delete cleanUser.teams
}
}
-
+
// Only add models if provided and non-empty
- if (user.models && typeof user.models === 'string' && user.models.trim() !== '') {
- cleanUser.models = user.models.split(',').map(model => model.trim()).filter(Boolean);
+ if (user.models && typeof user.models === "string" && user.models.trim() !== "") {
+ cleanUser.models = user.models
+ .split(",")
+ .map((model) => model.trim())
+ .filter(Boolean)
// Only include models if there's at least one valid model
if (cleanUser.models.length === 0) {
- delete cleanUser.models;
+ delete cleanUser.models
}
}
-
+
// Only add max_budget if it's a valid number
- if (user.max_budget && user.max_budget.toString().trim() !== '') {
- const budgetValue = parseFloat(user.max_budget.toString());
+ if (user.max_budget && user.max_budget.toString().trim() !== "") {
+ const budgetValue = parseFloat(user.max_budget.toString())
if (!isNaN(budgetValue) && budgetValue > 0) {
- cleanUser.max_budget = budgetValue;
+ cleanUser.max_budget = budgetValue
}
}
-
+
// Only add budget_duration if provided and non-empty
- if (user.budget_duration && user.budget_duration.trim() !== '') {
- cleanUser.budget_duration = user.budget_duration.trim();
+ if (user.budget_duration && user.budget_duration.trim() !== "") {
+ cleanUser.budget_duration = user.budget_duration.trim()
}
-
+
// Only add metadata if provided and non-empty
- if (user.metadata && typeof user.metadata === 'string' && user.metadata.trim() !== '') {
- cleanUser.metadata = user.metadata.trim();
+ if (user.metadata && typeof user.metadata === "string" && user.metadata.trim() !== "") {
+ cleanUser.metadata = user.metadata.trim()
}
- console.log('Sending user data:', cleanUser);
- const response = await userCreateCall(accessToken, null, cleanUser);
- console.log('Full response:', response);
-
+ console.log("Sending user data:", cleanUser)
+ const response = await userCreateCall(accessToken, null, cleanUser)
+ console.log("Full response:", response)
+
// Check if response has key or user_id, indicating success
if (response && (response.key || response.user_id)) {
- anySuccessful = true;
- console.log('Success case triggered');
- const user_id = response.data?.user_id || response.user_id;
-
+ anySuccessful = true
+ console.log("Success case triggered")
+ const user_id = response.data?.user_id || response.user_id
+
// Create invitation link for the user
try {
if (!uiSettings?.SSO_ENABLED) {
// Regular invitation flow
- const invitationData = await invitationCreateCall(accessToken, user_id);
- const invitationUrl = new URL(`/ui?invitation_id=${invitationData.id}`, baseUrl).toString();
-
- setParsedData(current =>
- current.map((u, i) =>
- i === index ? {
- ...u,
- status: 'success',
- key: response.key || response.user_id,
- invitation_link: invitationUrl
- } : u
- )
- );
+ const invitationData = await invitationCreateCall(accessToken, user_id)
+ const invitationUrl = new URL(`/ui?invitation_id=${invitationData.id}`, baseUrl).toString()
+
+ setParsedData((current) =>
+ current.map((u, i) =>
+ i === index
+ ? {
+ ...u,
+ status: "success",
+ key: response.key || response.user_id,
+ invitation_link: invitationUrl,
+ }
+ : u,
+ ),
+ )
} else {
// SSO flow - just use the base URL
- const invitationUrl = new URL("/ui", baseUrl).toString();
-
- setParsedData(current =>
- current.map((u, i) =>
- i === index ? {
- ...u,
- status: 'success',
- key: response.key || response.user_id,
- invitation_link: invitationUrl
- } : u
- )
- );
+ const invitationUrl = new URL("/ui", baseUrl).toString()
+
+ setParsedData((current) =>
+ current.map((u, i) =>
+ i === index
+ ? {
+ ...u,
+ status: "success",
+ key: response.key || response.user_id,
+ invitation_link: invitationUrl,
+ }
+ : u,
+ ),
+ )
}
} catch (inviteError) {
- console.error('Error creating invitation:', inviteError);
- setParsedData(current =>
- current.map((u, i) =>
- i === index ? {
- ...u,
- status: 'success',
- key: response.key || response.user_id,
- error: 'User created but failed to generate invitation link'
- } : u
- )
- );
+ console.error("Error creating invitation:", inviteError)
+ setParsedData((current) =>
+ current.map((u, i) =>
+ i === index
+ ? {
+ ...u,
+ status: "success",
+ key: response.key || response.user_id,
+ error: "User created but failed to generate invitation link",
+ }
+ : u,
+ ),
+ )
}
} else {
- console.log('Error case triggered');
- const errorMessage = response?.error || 'Failed to create user';
- console.log('Error message:', errorMessage);
- setParsedData(current =>
- current.map((u, i) =>
- i === index ? { ...u, status: 'failed', error: errorMessage } : u
+ console.log("Error case triggered")
+ const errorMessage = response?.error || "Failed to create user"
+ console.log("Error message:", errorMessage)
+ setParsedData((current) =>
+ current.map((u, i) => (i === index ? { ...u, status: "failed", error: errorMessage } : u)),
)
- );
}
} catch (error) {
- console.error('Caught error:', error);
- const errorMessage = (error as any)?.response?.data?.error ||
- (error as Error)?.message ||
- String(error);
- setParsedData(current =>
- current.map((u, i) =>
- i === index ? { ...u, status: 'failed', error: errorMessage } : u
- )
- );
+ console.error("Caught error:", error)
+ const errorMessage = (error as any)?.response?.data?.error || (error as Error)?.message || String(error)
+ setParsedData((current) =>
+ current.map((u, i) => (i === index ? { ...u, status: "failed", error: errorMessage } : u)),
+ )
}
}
- setIsProcessing(false);
-
+ setIsProcessing(false)
+
// Call the callback if any users were successfully created
if (anySuccessful && onUsersCreated) {
- onUsersCreated();
+ onUsersCreated()
}
- };
+ }
const downloadResults = () => {
- const results = parsedData.map(user => ({
+ const results = parsedData.map((user) => ({
user_email: user.user_email,
user_role: user.user_role,
status: user.status,
- key: user.key || '',
- invitation_link: user.invitation_link || '',
- error: user.error || ''
- }));
-
- const csv = Papa.unparse(results);
- const blob = new Blob([csv], { type: "text/csv" });
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = "bulk_users_results.csv";
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- window.URL.revokeObjectURL(url);
- };
+ key: user.key || "",
+ invitation_link: user.invitation_link || "",
+ error: user.error || "",
+ }))
+
+ const csv = Papa.unparse(results)
+ const blob = new Blob([csv], { type: "text/csv" })
+ const url = window.URL.createObjectURL(blob)
+ const a = document.createElement("a")
+ a.href = url
+ a.download = "bulk_users_results.csv"
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ window.URL.revokeObjectURL(url)
+ }
const columns = [
{
@@ -457,8 +483,8 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
key: "max_budget",
},
{
- title: 'Status',
- key: 'status',
+ title: "Status",
+ key: "status",
render: (_: any, record: UserData) => {
if (!record.isValid) {
return (
@@ -467,16 +493,14 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
<XCircleIcon className="h-5 w-5 text-red-500 mr-2" />
<span className="text-red-500">Invalid</span>
</div>
- {record.error && (
- <span className="text-sm text-red-500 ml-7">{record.error}</span>
- )}
+ {record.error && <span className="text-sm text-red-500 ml-7">{record.error}</span>}
</div>
- );
+ )
}
- if (!record.status || record.status === 'pending') {
- return <span className="text-gray-500">Pending</span>;
+ if (!record.status || record.status === "pending") {
+ return <span className="text-gray-500">Pending</span>
}
- if (record.status === 'success') {
+ if (record.status === "success") {
return (
<div>
<div className="flex items-center">
@@ -486,22 +510,18 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
{record.invitation_link && (
<div className="mt-1">
<div className="flex items-center">
- <span className="text-xs text-gray-500 truncate max-w-[150px]">
- {record.invitation_link}
- </span>
+ <span className="text-xs text-gray-500 truncate max-w-[150px]">{record.invitation_link}</span>
<CopyToClipboard
text={record.invitation_link}
onCopy={() => message.success("Invitation link copied!")}
>
- <button className="ml-1 text-blue-500 text-xs hover:text-blue-700">
- Copy
- </button>
+ <button className="ml-1 text-blue-500 text-xs hover:text-blue-700">Copy</button>
</CopyToClipboard>
</div>
</div>
)}
</div>
- );
+ )
}
return (
<div>
@@ -509,29 +529,25 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
<XCircleIcon className="h-5 w-5 text-red-500 mr-2" />
<span className="text-red-500">Failed</span>
</div>
- {record.error && (
- <span className="text-sm text-red-500 ml-7">
- {JSON.stringify(record.error)}
- </span>
- )}
+ {record.error && <span className="text-sm text-red-500 ml-7">{JSON.stringify(record.error)}</span>}
</div>
- );
+ )
},
},
- ];
+ ]
return (
<>
- <TremorButton className="mx-auto mb-0" onClick={() => setIsModalVisible(true)}>
+ <TremorButton className="mb-0" onClick={() => setIsModalVisible(true)}>
+ Bulk Invite Users
</TremorButton>
-
+
<Modal
title="Bulk Invite Users"
visible={isModalVisible}
width={800}
onCancel={() => setIsModalVisible(false)}
- bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }}
+ bodyStyle={{ maxHeight: "70vh", overflow: "auto" }}
footer={null}
>
<div className="flex flex-col">
@@ -539,10 +555,12 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
{parsedData.length === 0 ? (
<div className="mb-6">
<div className="flex items-center mb-4">
- <div className="w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3">1</div>
+ <div className="w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3">
+ 1
+ </div>
<h3 className="text-lg font-medium">Download and fill the template</h3>
</div>
-
+
<div className="ml-11 mb-6">
<p className="mb-4">Add multiple users at once by following these steps:</p>
<ol className="list-decimal list-inside space-y-2 ml-2 mb-4">
@@ -551,7 +569,7 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
<li>Save the file and upload it here</li>
<li>After creation, download the results file containing the API keys for each user</li>
</ol>
-
+
<div className="bg-gray-50 p-4 rounded-md border border-gray-200 mb-4">
<h4 className="font-medium mb-2">Template Column Names</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
@@ -566,14 +584,19 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
<div className="w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"></div>
<div>
<p className="font-medium">user_role</p>
- <p className="text-sm text-gray-600">User&apos;s role (one of: &quot;proxy_admin&quot;, &quot;proxy_admin_view_only&quot;, &quot;internal_user&quot;, &quot;internal_user_view_only&quot;)</p>
+ <p className="text-sm text-gray-600">
+ User&apos;s role (one of: &quot;proxy_admin&quot;, &quot;proxy_admin_view_only&quot;,
+ &quot;internal_user&quot;, &quot;internal_user_view_only&quot;)
+ </p>
</div>
</div>
<div className="flex items-start">
<div className="w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"></div>
<div>
<p className="font-medium">teams</p>
- <p className="text-sm text-gray-600">Comma-separated team IDs (e.g., &quot;team-1,team-2&quot;)</p>
+ <p className="text-sm text-gray-600">
+ Comma-separated team IDs (e.g., &quot;team-1,team-2&quot;)
+ </p>
</div>
</div>
<div className="flex items-start">
@@ -587,36 +610,40 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
<div className="w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"></div>
<div>
<p className="font-medium">budget_duration</p>
- <p className="text-sm text-gray-600">Budget reset period (e.g., &quot;30d&quot;, &quot;1mo&quot;)</p>
+ <p className="text-sm text-gray-600">
+ Budget reset period (e.g., &quot;30d&quot;, &quot;1mo&quot;)
+ </p>
</div>
</div>
<div className="flex items-start">
<div className="w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"></div>
<div>
<p className="font-medium">models</p>
- <p className="text-sm text-gray-600">Comma-separated allowed models (e.g., &quot;gpt-3.5-turbo,gpt-4&quot;)</p>
+ <p className="text-sm text-gray-600">
+ Comma-separated allowed models (e.g., &quot;gpt-3.5-turbo,gpt-4&quot;)
+ </p>
</div>
</div>
</div>
</div>
-
- <TremorButton
- onClick={downloadTemplate}
- size="lg"
- className="w-full md:w-auto"
- >
+
+ <TremorButton onClick={downloadTemplate} size="lg" className="w-full md:w-auto">
<DownloadOutlined className="mr-2" /> Download CSV Template
</TremorButton>
</div>
-
+
<div className="flex items-center mb-4">
- <div className="w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3">2</div>
+ <div className="w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3">
+ 2
+ </div>
<h3 className="text-lg font-medium">Upload your completed CSV</h3>
</div>
-
+
<div className="ml-11">
{selectedFile ? (
- <div className={`mb-4 p-4 rounded-md border ${fileError ? 'bg-red-50 border-red-200' : 'bg-blue-50 border-blue-200'}`}>
+ <div
+ className={`mb-4 p-4 rounded-md border ${fileError ? "bg-red-50 border-red-200" : "bg-blue-50 border-blue-200"}`}
+ >
<div className="flex items-center justify-between">
<div className="flex items-center">
{fileError ? (
@@ -642,28 +669,25 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
<DeleteOutlined className="mr-1" /> Remove
</TremorButton>
</div>
-
+
{fileError ? (
<div className="mt-3 text-red-600 text-sm flex items-start">
<WarningOutlined className="mr-2 mt-0.5" />
<span>{fileError}</span>
</div>
- ) : !csvStructureError && (
- <div className="mt-3 flex items-center">
- <div className="w-full bg-gray-200 rounded-full h-1.5">
- <div className="bg-blue-500 h-1.5 rounded-full w-full animate-pulse"></div>
+ ) : (
+ !csvStructureError && (
+ <div className="mt-3 flex items-center">
+ <div className="w-full bg-gray-200 rounded-full h-1.5">
+ <div className="bg-blue-500 h-1.5 rounded-full w-full animate-pulse"></div>
+ </div>
+ <span className="ml-2 text-xs text-blue-600">Processing...</span>
</div>
- <span className="ml-2 text-xs text-blue-600">Processing...</span>
- </div>
+ )
)}
</div>
) : (
- <Upload
- beforeUpload={handleFileUpload}
- accept=".csv"
- maxCount={1}
- showUploadList={false}
- >
+ <Upload beforeUpload={handleFileUpload} accept=".csv" maxCount={1} showUploadList={false}>
<div className="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer">
<UploadOutlined className="text-3xl text-gray-400 mb-2" />
<p className="mb-1">Drag and drop your CSV file here</p>
@@ -673,13 +697,15 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
</div>
</Upload>
)}
-
+
{csvStructureError && (
<div className="mb-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md">
<div className="flex items-start">
<ExclamationIcon className="h-5 w-5 text-yellow-500 mr-2 mt-0.5" />
<div>
- <Typography.Text strong className="text-yellow-800">CSV Structure Error</Typography.Text>
+ <Typography.Text strong className="text-yellow-800">
+ CSV Structure Error
+ </Typography.Text>
<Typography.Paragraph className="text-yellow-700 mt-1 mb-0">
{csvStructureError}
</Typography.Paragraph>
@@ -695,24 +721,29 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
) : (
<div className="mb-6">
<div className="flex items-center mb-4">
- <div className="w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3">3</div>
+ <div className="w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3">
+ 3
+ </div>
<h3 className="text-lg font-medium">
- {parsedData.some(user => user.status === 'success' || user.status === 'failed')
- ? "User Creation Results"
+ {parsedData.some((user) => user.status === "success" || user.status === "failed")
+ ? "User Creation Results"
: "Review and create users"}
</h3>
</div>
-
+
{parseError && (
<div className="ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md">
<div className="flex items-start">
<WarningOutlined className="text-red-500 mr-2 mt-1" />
<div>
<Text className="text-red-600 font-medium">{parseError}</Text>
- {parsedData.some(user => !user.isValid) && (
+ {parsedData.some((user) => !user.isValid) && (
<ul className="mt-2 list-disc list-inside text-red-600 text-sm">
<li>Check the table below for specific errors in each row</li>
- <li>Common issues include invalid email formats, missing required fields, or incorrect role values</li>
+ <li>
+ Common issues include invalid email formats, missing required fields, or incorrect role
+ values
+ </li>
<li>Fix these issues in your CSV file and upload again</li>
</ul>
)}
@@ -720,19 +751,19 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
</div>
</div>
)}
-
+
<div className="ml-11">
<div className="flex justify-between items-center mb-3">
<div className="flex items-center">
- {parsedData.some(user => user.status === 'success' || user.status === 'failed') ? (
+ {parsedData.some((user) => user.status === "success" || user.status === "failed") ? (
<div className="flex items-center">
<Text className="text-lg font-medium mr-3">Creation Summary</Text>
<Text className="text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2">
- {parsedData.filter(d => d.status === 'success').length} Successful
+ {parsedData.filter((d) => d.status === "success").length} Successful
</Text>
- {parsedData.some(d => d.status === 'failed') && (
+ {parsedData.some((d) => d.status === "failed") && (
<Text className="text-sm bg-red-100 text-red-800 px-2 py-1 rounded">
- {parsedData.filter(d => d.status === 'failed').length} Failed
+ {parsedData.filter((d) => d.status === "failed").length} Failed
</Text>
)}
</div>
@@ -740,34 +771,34 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
<div className="flex items-center">
<Text className="text-lg font-medium mr-3">User Preview</Text>
<Text className="text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded">
- {parsedData.filter(d => d.isValid).length} of {parsedData.length} users valid
+ {parsedData.filter((d) => d.isValid).length} of {parsedData.length} users valid
</Text>
</div>
)}
</div>
-
- {!parsedData.some(user => user.status === 'success' || user.status === 'failed') && (
+
+ {!parsedData.some((user) => user.status === "success" || user.status === "failed") && (
<div className="flex space-x-3">
- <TremorButton
+ <TremorButton
onClick={() => {
- setParsedData([]);
- setParseError(null);
- }}
+ setParsedData([])
+ setParseError(null)
+ }}
variant="secondary"
>
Back
</TremorButton>
<TremorButton
onClick={handleBulkCreate}
- disabled={parsedData.filter(d => d.isValid).length === 0 || isProcessing}
+ disabled={parsedData.filter((d) => d.isValid).length === 0 || isProcessing}
>
- {isProcessing ? 'Creating...' : `Create ${parsedData.filter(d => d.isValid).length} Users`}
+ {isProcessing ? "Creating..." : `Create ${parsedData.filter((d) => d.isValid).length} Users`}
</TremorButton>
</div>
)}
</div>
-
- {parsedData.some(user => user.status === 'success') && (
+
+ {parsedData.some((user) => user.status === "success") && (
<div className="mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md">
<div className="flex items-start">
<div className="mr-3 mt-1">
@@ -776,30 +807,31 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
<div>
<Text className="font-medium text-blue-800">User creation complete</Text>
<Text className="block text-sm text-blue-700 mt-1">
- <span className="font-medium">Next step:</span> Download the credentials file containing API keys and invitation links.
- Users will need these API keys to make LLM requests through LiteLLM.
+ <span className="font-medium">Next step:</span> Download the credentials file containing API
+ keys and invitation links. Users will need these API keys to make LLM requests through
+ LiteLLM.
</Text>
</div>
</div>
</div>
)}
-
+
<Table
dataSource={parsedData}
columns={columns}
size="small"
pagination={{ pageSize: 5 }}
scroll={{ y: 300 }}
- rowClassName={(record) => !record.isValid ? 'bg-red-50' : ''}
+ rowClassName={(record) => (!record.isValid ? "bg-red-50" : "")}
/>
-
- {!parsedData.some(user => user.status === 'success' || user.status === 'failed') && (
+
+ {!parsedData.some((user) => user.status === "success" || user.status === "failed") && (
<div className="flex justify-end mt-4">
- <TremorButton
+ <TremorButton
onClick={() => {
- setParsedData([]);
- setParseError(null);
- }}
+ setParsedData([])
+ setParseError(null)
+ }}
variant="secondary"
className="mr-3"
>
@@ -807,30 +839,26 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
</TremorButton>
<TremorButton
onClick={handleBulkCreate}
- disabled={parsedData.filter(d => d.isValid).length === 0 || isProcessing}
+ disabled={parsedData.filter((d) => d.isValid).length === 0 || isProcessing}
>
- {isProcessing ? 'Creating...' : `Create ${parsedData.filter(d => d.isValid).length} Users`}
+ {isProcessing ? "Creating..." : `Create ${parsedData.filter((d) => d.isValid).length} Users`}
</TremorButton>
</div>
)}
-
- {parsedData.some(user => user.status === 'success' || user.status === 'failed') && (
+
+ {parsedData.some((user) => user.status === "success" || user.status === "failed") && (
<div className="flex justify-end mt-4">
- <TremorButton
+ <TremorButton
onClick={() => {
- setParsedData([]);
- setParseError(null);
- }}
+ setParsedData([])
+ setParseError(null)
+ }}
variant="secondary"
className="mr-3"
>
Start New Bulk Import
</TremorButton>
- <TremorButton
- onClick={downloadResults}
- variant="primary"
- className="flex items-center"
- >
+ <TremorButton onClick={downloadResults} variant="primary" className="flex items-center">
<DownloadOutlined className="mr-2" /> Download User Credentials
</TremorButton>
</div>
@@ -841,7 +869,7 @@ const BulkCreateUsersButton: React.FC<BulkCreateUsersProps> = ({
</div>
</Modal>
</>
- );
-};
+ )
+}
-export default BulkCreateUsersButton;
\ No newline at end of file
+export default BulkCreateUsersButton
diff --git a/ui/litellm-dashboard/src/components/create_user_button.tsx b/ui/litellm-dashboard/src/components/create_user_button.tsx
index 5f7e93deb8d..3edfe93a076 100644
--- a/ui/litellm-dashboard/src/components/create_user_button.tsx
+++ b/ui/litellm-dashboard/src/components/create_user_button.tsx
@@ -1,47 +1,47 @@
-import React, { useState, useEffect } from "react";
-import { useRouter } from "next/navigation";
+import React, { useState, useEffect } from "react"
+import { useRouter } from "next/navigation"
+import { Button, Modal, Form, Input, message, Select, InputNumber, Select as Select2 } from "antd"
import {
- Button,
- Modal,
- Form,
- Input,
- message,
- Select,
- InputNumber,
- Select as Select2,
-} from "antd";
-import { Button as Button2, Text, TextInput, SelectItem, Accordion, AccordionHeader, AccordionBody, Title, } from "@tremor/react";
-import OnboardingModal from "./onboarding_link";
-import { InvitationLink } from "./onboarding_link";
+ Button as Button2,
+ Text,
+ TextInput,
+ SelectItem,
+ Accordion,
+ AccordionHeader,
+ AccordionBody,
+ Title,
+} from "@tremor/react"
+import OnboardingModal from "./onboarding_link"
+import { InvitationLink } from "./onboarding_link"
import {
userCreateCall,
modelAvailableCall,
invitationCreateCall,
getProxyUISettings,
getProxyBaseUrl,
-} from "./networking";
-import BulkCreateUsers from "./bulk_create_users_button";
-const { Option } = Select;
-import { Tooltip } from "antd";
-import { InfoCircleOutlined } from '@ant-design/icons';
-import { getModelDisplayName } from "./key_team_helpers/fetch_available_models_team_key";
-import { useQueryClient } from "@tanstack/react-query";
+} from "./networking"
+import BulkCreateUsers from "./bulk_create_users_button"
+const { Option } = Select
+import { Tooltip } from "antd"
+import { InfoCircleOutlined } from "@ant-design/icons"
+import { getModelDisplayName } from "./key_team_helpers/fetch_available_models_team_key"
+import { useQueryClient } from "@tanstack/react-query"
interface CreateuserProps {
- userID: string;
- accessToken: string;
- teams: any[] | null;
- possibleUIRoles: null | Record<string, Record<string, string>>;
- onUserCreated?: (userId: string) => void;
- isEmbedded?: boolean;
+ userID: string
+ accessToken: string
+ teams: any[] | null
+ possibleUIRoles: null | Record<string, Record<string, string>>
+ onUserCreated?: (userId: string) => void
+ isEmbedded?: boolean
}
// Define an interface for the UI settings
interface UISettings {
- PROXY_BASE_URL: string | null;
- PROXY_LOGOUT_URL: string | null;
- DEFAULT_TEAM_DISABLED: boolean;
- SSO_ENABLED: boolean;
+ PROXY_BASE_URL: string | null
+ PROXY_LOGOUT_URL: string | null
+ DEFAULT_TEAM_DISABLED: boolean
+ SSO_ENABLED: boolean
}
const Createuser: React.FC<CreateuserProps> = ({
@@ -52,97 +52,91 @@ const Createuser: React.FC<CreateuserProps> = ({
onUserCreated,
isEmbedded = false,
}) => {
- const queryClient = useQueryClient();
- const [uiSettings, setUISettings] = useState<UISettings | null>(null);
- const [form] = Form.useForm();
- const [isModalVisible, setIsModalVisible] = useState(false);
- const [apiuser, setApiuser] = useState<boolean>(false);
- const [userModels, setUserModels] = useState<string[]>([]);
- const [isInvitationLinkModalVisible, setIsInvitationLinkModalVisible] =
- useState(false);
- const [invitationLinkData, setInvitationLinkData] =
- useState<InvitationLink | null>(null);
- const [baseUrl, setBaseUrl] = useState<string | null>(null);
+ const queryClient = useQueryClient()
+ const [uiSettings, setUISettings] = useState<UISettings | null>(null)
+ const [form] = Form.useForm()
+ const [isModalVisible, setIsModalVisible] = useState(false)
+ const [apiuser, setApiuser] = useState<boolean>(false)
+ const [userModels, setUserModels] = useState<string[]>([])
+ const [isInvitationLinkModalVisible, setIsInvitationLinkModalVisible] = useState(false)
+ const [invitationLinkData, setInvitationLinkData] = useState<InvitationLink | null>(null)
+ const [baseUrl, setBaseUrl] = useState<string | null>(null)
// get all models
useEffect(() => {
const fetchData = async () => {
try {
- const userRole = "any"; // You may need to get the user role dynamically
- const modelDataResponse = await modelAvailableCall(
- accessToken,
- userID,
- userRole,
- );
+ const userRole = "any" // You may need to get the user role dynamically
+ const modelDataResponse = await modelAvailableCall(accessToken, userID, userRole)
// Assuming modelDataResponse.data contains an array of model objects with a 'model_name' property
- const availableModels = [];
+ const availableModels = []
for (let i = 0; i < modelDataResponse.data.length; i++) {
- const model = modelDataResponse.data[i];
- availableModels.push(model.id);
+ const model = modelDataResponse.data[i]
+ availableModels.push(model.id)
}
- console.log("Model data response:", modelDataResponse.data);
- console.log("Available models:", availableModels);
+ console.log("Model data response:", modelDataResponse.data)
+ console.log("Available models:", availableModels)
// Assuming modelDataResponse.data contains an array of model names
- setUserModels(availableModels);
+ setUserModels(availableModels)
// get ui settings
- const uiSettingsResponse = await getProxyUISettings(accessToken);
- console.log("uiSettingsResponse:", uiSettingsResponse);
+ const uiSettingsResponse = await getProxyUISettings(accessToken)
+ console.log("uiSettingsResponse:", uiSettingsResponse)
- setUISettings(uiSettingsResponse);
+ setUISettings(uiSettingsResponse)
} catch (error) {
- console.error("Error fetching model data:", error);
+ console.error("Error fetching model data:", error)
}
- };
+ }
- setBaseUrl(getProxyBaseUrl());
+ setBaseUrl(getProxyBaseUrl())
- fetchData(); // Call the function to fetch model data when the component mounts
- }, []); // Empty dependency array to run only once
+ fetchData() // Call the function to fetch model data when the component mounts
+ }, []) // Empty dependency array to run only once
const handleOk = () => {
- setIsModalVisible(false);
- form.resetFields();
- };
+ setIsModalVisible(false)
+ form.resetFields()
+ }
const handleCancel = () => {
- setIsModalVisible(false);
- setApiuser(false);
- form.resetFields();
- };
+ setIsModalVisible(false)
+ setApiuser(false)
+ form.resetFields()
+ }
- const handleCreate = async (formValues: { user_id: string, models?: string[], user_role: string }) => {
+ const handleCreate = async (formValues: { user_id: string; models?: string[]; user_role: string }) => {
try {
- message.info("Making API Call");
+ message.info("Making API Call")
if (!isEmbedded) {
- setIsModalVisible(true);
+ setIsModalVisible(true)
}
if ((!formValues.models || formValues.models.length === 0) && formValues.user_role !== "proxy_admin") {
console.log("formValues.user_role", formValues.user_role)
// If models is empty or undefined, set it to "no-default-models"
- formValues.models = ["no-default-models"];
+ formValues.models = ["no-default-models"]
}
- console.log("formValues in create user:", formValues);
- const response = await userCreateCall(accessToken, null, formValues);
- await queryClient.invalidateQueries({ queryKey: ['userList'] })
- console.log("user create Response:", response);
- setApiuser(true);
- const user_id = response.data?.user_id || response.user_id;
+ console.log("formValues in create user:", formValues)
+ const response = await userCreateCall(accessToken, null, formValues)
+ await queryClient.invalidateQueries({ queryKey: ["userList"] })
+ console.log("user create Response:", response)
+ setApiuser(true)
+ const user_id = response.data?.user_id || response.user_id
// Call the callback if provided (for embedded mode)
if (onUserCreated && isEmbedded) {
- onUserCreated(user_id);
- form.resetFields();
- return; // Skip the invitation flow when embedded
+ onUserCreated(user_id)
+ form.resetFields()
+ return // Skip the invitation flow when embedded
}
// only do invite link flow if sso is not enabled
if (!uiSettings?.SSO_ENABLED) {
invitationCreateCall(accessToken, user_id).then((data) => {
- data.has_user_setup_sso = false;
- setInvitationLinkData(data);
- setIsInvitationLinkModalVisible(true);
- });
+ data.has_user_setup_sso = false
+ setInvitationLinkData(data)
+ setIsInvitationLinkModalVisible(true)
+ })
} else {
// create an InvitationLink Object for this user for the SSO flow
// for SSO the invite link is the proxy base url since the User just needs to login
@@ -157,52 +151,41 @@ const Createuser: React.FC<CreateuserProps> = ({
updated_at: new Date(),
updated_by: userID,
has_user_setup_sso: true,
- };
- setInvitationLinkData(invitationLink);
- setIsInvitationLinkModalVisible(true);
+ }
+ setInvitationLinkData(invitationLink)
+ setIsInvitationLinkModalVisible(true)
}
- message.success("API user Created");
- form.resetFields();
- localStorage.removeItem("userData" + userID);
+ message.success("API user Created")
+ form.resetFields()
+ localStorage.removeItem("userData" + userID)
} catch (error: any) {
- const errorMessage = error.response?.data?.detail || error?.message || "Error creating the user";
- message.error(errorMessage);
- console.error("Error creating the user:", error);
+ const errorMessage = error.response?.data?.detail || error?.message || "Error creating the user"
+ message.error(errorMessage)
+ console.error("Error creating the user:", error)
}
- };
+ }
// Modify the return statement to handle embedded mode
if (isEmbedded) {
return (
- <Form
- form={form}
- onFinish={handleCreate}
- labelCol={{ span: 8 }}
- wrapperCol={{ span: 16 }}
- labelAlign="left"
- >
+ <Form form={form} onFinish={handleCreate} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} labelAlign="left">
<Form.Item label="User Email" name="user_email">
<TextInput placeholder="" />
</Form.Item>
<Form.Item label="User Role" name="user_role">
<Select2>
{possibleUIRoles &&
- Object.entries(possibleUIRoles).map(
- ([role, { ui_label, description }]) => (
- <SelectItem key={role} value={role} title={ui_label}>
- <div className="flex">
- {ui_label}{" "}
- <p
- className="ml-2"
- style={{ color: "gray", fontSize: "12px" }}
- >
- {description}
- </p>
- </div>
- </SelectItem>
- ),
- )}
+ Object.entries(possibleUIRoles).map(([role, { ui_label, description }]) => (
+ <SelectItem key={role} value={role} title={ui_label}>
+ <div className="flex">
+ {ui_label}{" "}
+ <p className="ml-2" style={{ color: "gray", fontSize: "12px" }}>
+ {description}
+ </p>
+ </div>
+ </SelectItem>
+ ))}
</Select2>
</Form.Item>
<Form.Item label="Team ID" name="team_id">
@@ -224,25 +207,21 @@ const Createuser: React.FC<CreateuserProps> = ({
<Form.Item label="Metadata" name="metadata">
<Input.TextArea rows={4} placeholder="Enter metadata as JSON" />
</Form.Item>
-
+
<div style={{ textAlign: "right", marginTop: "10px" }}>
<Button htmlType="submit">Create User</Button>
</div>
</Form>
- );
+ )
}
// Original return for standalone mode
return (
<div className="flex gap-2">
- <Button2 className="mx-auto mb-0" onClick={() => setIsModalVisible(true)}>
+ <Button2 className="mb-0" onClick={() => setIsModalVisible(true)}>
+ Invite User
</Button2>
- <BulkCreateUsers
- accessToken={accessToken}
- teams={teams}
- possibleUIRoles={possibleUIRoles}
- />
+ <BulkCreateUsers accessToken={accessToken} teams={teams} possibleUIRoles={possibleUIRoles} />
<Modal
title="Invite User"
visible={isModalVisible}
@@ -252,46 +231,42 @@ const Createuser: React.FC<CreateuserProps> = ({
onCancel={handleCancel}
>
<Text className="mb-1">Create a User who can own keys</Text>
- <Form
- form={form}
- onFinish={handleCreate}
- labelCol={{ span: 8 }}
- wrapperCol={{ span: 16 }}
- labelAlign="left"
- >
+ <Form form={form} onFinish={handleCreate} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} labelAlign="left">
<Form.Item label="User Email" name="user_email">
<TextInput placeholder="" />
</Form.Item>
- <Form.Item label={
- <span>
- Global Proxy Role{' '}
- <Tooltip title="This is the role that the user will globally on the proxy. This role is independent of any team/org specific roles.">
- <InfoCircleOutlined/>
- </Tooltip>
- </span>
- }
- name="user_role">
+ <Form.Item
+ label={
+ <span>
+ Global Proxy Role{" "}
+ <Tooltip title="This is the role that the user will globally on the proxy. This role is independent of any team/org specific roles.">
+ <InfoCircleOutlined />
+ </Tooltip>
+ </span>
+ }
+ name="user_role"
+ >
<Select2>
{possibleUIRoles &&
- Object.entries(possibleUIRoles).map(
- ([role, { ui_label, description }]) => (
- <SelectItem key={role} value={role} title={ui_label}>
- <div className="flex">
- {ui_label}{" "}
- <p
- className="ml-2"
- style={{ color: "gray", fontSize: "12px" }}
- >
- {description}
- </p>
- </div>
- </SelectItem>
- ),
- )}
+ Object.entries(possibleUIRoles).map(([role, { ui_label, description }]) => (
+ <SelectItem key={role} value={role} title={ui_label}>
+ <div className="flex">
+ {ui_label}{" "}
+ <p className="ml-2" style={{ color: "gray", fontSize: "12px" }}>
+ {description}
+ </p>
+ </div>
+ </SelectItem>
+ ))}
</Select2>
</Form.Item>
-
- <Form.Item label="Team ID" className="gap-2" name="team_id" help="If selected, user will be added as a 'user' role to the team.">
+
+ <Form.Item
+ label="Team ID"
+ className="gap-2"
+ name="team_id"
+ help="If selected, user will be added as a 'user' role to the team."
+ >
<Select placeholder="Select Team ID" style={{ width: "100%" }}>
{teams ? (
teams.map((team: any) => (
@@ -311,38 +286,36 @@ const Createuser: React.FC<CreateuserProps> = ({
<Input.TextArea rows={4} placeholder="Enter metadata as JSON" />
</Form.Item>
<Accordion>
- <AccordionHeader>
- <Title>Personal Key Creation</Title>
- </AccordionHeader>
- <AccordionBody>
- <Form.Item className="gap-2" label={
- <span>
- Models{' '}
- <Tooltip title="Models user has access to, outside of team scope.">
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
- </Tooltip>
- </span>
- } name="models" help="Models user has access to, outside of team scope.">
- <Select2
- mode="multiple"
- placeholder="Select models"
- style={{ width: "100%" }}
+ <AccordionHeader>
+ <Title>Personal Key Creation</Title>
+ </AccordionHeader>
+ <AccordionBody>
+ <Form.Item
+ className="gap-2"
+ label={
+ <span>
+ Models{" "}
+ <Tooltip title="Models user has access to, outside of team scope.">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="models"
+ help="Models user has access to, outside of team scope."
>
- <Select2.Option
- key="all-proxy-models"
- value="all-proxy-models"
- >
- All Proxy Models
- </Select2.Option>
- {userModels.map((model) => (
- <Select2.Option key={model} value={model}>
- {getModelDisplayName(model)}
+ <Select2 mode="multiple" placeholder="Select models" style={{ width: "100%" }}>
+ <Select2.Option key="all-proxy-models" value="all-proxy-models">
+ All Proxy Models
</Select2.Option>
- ))}
- </Select2>
- </Form.Item>
- </AccordionBody>
- </Accordion>
+ {userModels.map((model) => (
+ <Select2.Option key={model} value={model}>
+ {getModelDisplayName(model)}
+ </Select2.Option>
+ ))}
+ </Select2>
+ </Form.Item>
+ </AccordionBody>
+ </Accordion>
<div style={{ textAlign: "right", marginTop: "10px" }}>
<Button htmlType="submit">Create User</Button>
</div>
@@ -357,7 +330,7 @@ const Createuser: React.FC<CreateuserProps> = ({
/>
)}
</div>
- );
-};
+ )
+}
-export default Createuser;
+export default Createuser
diff --git a/ui/litellm-dashboard/src/components/guardrails.tsx b/ui/litellm-dashboard/src/components/guardrails.tsx
index d82da325c78..8f7d8fb3a1d 100644
--- a/ui/litellm-dashboard/src/components/guardrails.tsx
+++ b/ui/litellm-dashboard/src/components/guardrails.tsx
@@ -1,136 +1,135 @@
-import React, { useState, useEffect } from "react";
-import {
- Card,
- Text,
- Button,
- Icon,
- TextInput,
-} from "@tremor/react";
-import {
- PlusIcon,
-} from "@heroicons/react/outline";
-import { Modal, message } from "antd";
-import { getGuardrailsList, deleteGuardrailCall } from "./networking";
-import AddGuardrailForm from "./guardrails/add_guardrail_form";
-import GuardrailTable from "./guardrails/guardrail_table";
-import { isAdminRole } from "@/utils/roles";
+import React, { useState, useEffect } from "react"
+import { Card, Text, Button, Icon, TextInput } from "@tremor/react"
+import { PlusIcon } from "@heroicons/react/outline"
+import { Modal, message } from "antd"
+import { getGuardrailsList, deleteGuardrailCall } from "./networking"
+import AddGuardrailForm from "./guardrails/add_guardrail_form"
+import GuardrailTable from "./guardrails/guardrail_table"
+import { isAdminRole } from "@/utils/roles"
+import GuardrailInfoView from "./guardrails/guardrail_info"
interface GuardrailsPanelProps {
- accessToken: string | null;
- userRole?: string;
+ accessToken: string | null
+ userRole?: string
}
interface GuardrailItem {
- guardrail_id?: string;
- guardrail_name: string | null;
+ guardrail_id?: string
+ guardrail_name: string | null
litellm_params: {
- guardrail: string;
- mode: string;
- default_on: boolean;
- };
- guardrail_info: Record<string, any> | null;
- created_at?: string;
- updated_at?: string;
+ guardrail: string
+ mode: string
+ default_on: boolean
+ }
+ guardrail_info: Record<string, any> | null
+ created_at?: string
+ updated_at?: string
}
interface GuardrailsResponse {
- guardrails: GuardrailItem[];
+ guardrails: GuardrailItem[]
}
const GuardrailsPanel: React.FC<GuardrailsPanelProps> = ({ accessToken, userRole }) => {
- const [guardrailsList, setGuardrailsList] = useState<GuardrailItem[]>([]);
- const [isAddModalVisible, setIsAddModalVisible] = useState(false);
- const [isLoading, setIsLoading] = useState(false);
- const [isDeleting, setIsDeleting] = useState(false);
- const [guardrailToDelete, setGuardrailToDelete] = useState<{id: string, name: string} | null>(null);
- const [isViewingGuardrailInfo, setIsViewingGuardrailInfo] = useState(false);
-
- const isAdmin = userRole ? isAdminRole(userRole) : false;
+ const [guardrailsList, setGuardrailsList] = useState<GuardrailItem[]>([])
+ const [isAddModalVisible, setIsAddModalVisible] = useState(false)
+ const [isLoading, setIsLoading] = useState(false)
+ const [isDeleting, setIsDeleting] = useState(false)
+ const [guardrailToDelete, setGuardrailToDelete] = useState<{ id: string; name: string } | null>(null)
+ const [selectedGuardrailId, setSelectedGuardrailId] = useState<string | null>(null)
+
+ const isAdmin = userRole ? isAdminRole(userRole) : false
const fetchGuardrails = async () => {
if (!accessToken) {
- return;
+ return
}
-
- setIsLoading(true);
+
+ setIsLoading(true)
try {
- const response: GuardrailsResponse = await getGuardrailsList(accessToken);
- console.log(`guardrails: ${JSON.stringify(response)}`);
- setGuardrailsList(response.guardrails);
+ const response: GuardrailsResponse = await getGuardrailsList(accessToken)
+ console.log(`guardrails: ${JSON.stringify(response)}`)
+ setGuardrailsList(response.guardrails)
} catch (error) {
- console.error('Error fetching guardrails:', error);
+ console.error("Error fetching guardrails:", error)
} finally {
- setIsLoading(false);
+ setIsLoading(false)
}
- };
+ }
useEffect(() => {
- fetchGuardrails();
- }, [accessToken]);
+ fetchGuardrails()
+ }, [accessToken])
const handleAddGuardrail = () => {
- setIsAddModalVisible(true);
- };
+ if (selectedGuardrailId) {
+ setSelectedGuardrailId(null)
+ }
+ setIsAddModalVisible(true)
+ }
const handleCloseModal = () => {
- setIsAddModalVisible(false);
- };
+ setIsAddModalVisible(false)
+ }
const handleSuccess = () => {
- fetchGuardrails();
- };
+ fetchGuardrails()
+ }
const handleDeleteClick = (guardrailId: string, guardrailName: string) => {
- setGuardrailToDelete({id: guardrailId, name: guardrailName});
- };
+ setGuardrailToDelete({ id: guardrailId, name: guardrailName })
+ }
const handleDeleteConfirm = async () => {
- if (!guardrailToDelete || !accessToken) return;
-
+ if (!guardrailToDelete || !accessToken) return
+
// Log removed to maintain clean production code
- setIsDeleting(true);
+ setIsDeleting(true)
try {
- await deleteGuardrailCall(accessToken, guardrailToDelete.id);
- message.success(`Guardrail "${guardrailToDelete.name}" deleted successfully`);
- fetchGuardrails(); // Refresh the list
+ await deleteGuardrailCall(accessToken, guardrailToDelete.id)
+ message.success(`Guardrail "${guardrailToDelete.name}" deleted successfully`)
+ fetchGuardrails() // Refresh the list
} catch (error) {
- console.error('Error deleting guardrail:', error);
- message.error('Failed to delete guardrail');
+ console.error("Error deleting guardrail:", error)
+ message.error("Failed to delete guardrail")
} finally {
- setIsDeleting(false);
- setGuardrailToDelete(null);
+ setIsDeleting(false)
+ setGuardrailToDelete(null)
}
- };
+ }
const handleDeleteCancel = () => {
- setGuardrailToDelete(null);
- };
+ setGuardrailToDelete(null)
+ }
return (
<div className="w-full mx-auto flex-auto overflow-y-auto m-8 p-2">
- {!isViewingGuardrailInfo && (
- <div className="flex justify-between items-center mb-4">
- <Button
- icon={PlusIcon}
- onClick={handleAddGuardrail}
- disabled={!accessToken}
- >
- Add Guardrail
- </Button>
- </div>
+ <div className="flex justify-between items-center mb-4">
+ <Button onClick={handleAddGuardrail} disabled={!accessToken}>
+ + Add New Guardrail
+ </Button>
+ </div>
+
+ {selectedGuardrailId ? (
+ <GuardrailInfoView
+ guardrailId={selectedGuardrailId}
+ onClose={() => setSelectedGuardrailId(null)}
+ accessToken={accessToken}
+ isAdmin={isAdmin}
+ />
+ ) : (
+ <GuardrailTable
+ guardrailsList={guardrailsList}
+ isLoading={isLoading}
+ onDeleteClick={handleDeleteClick}
+ accessToken={accessToken}
+ onGuardrailUpdated={fetchGuardrails}
+ isAdmin={isAdmin}
+ onGuardrailClick={(id) => setSelectedGuardrailId(id)}
+ />
)}
-
- <GuardrailTable
- guardrailsList={guardrailsList}
- isLoading={isLoading}
- onDeleteClick={handleDeleteClick}
- accessToken={accessToken}
- onGuardrailUpdated={fetchGuardrails}
- isAdmin={isAdmin}
- onShowGuardrailInfo={setIsViewingGuardrailInfo}
- />
- <AddGuardrailForm
+ <AddGuardrailForm
visible={isAddModalVisible}
onClose={handleCloseModal}
accessToken={accessToken}
@@ -152,7 +151,7 @@ const GuardrailsPanel: React.FC<GuardrailsPanelProps> = ({ accessToken, userRole
</Modal>
)}
</div>
- );
-};
+ )
+}
-export default GuardrailsPanel;
\ No newline at end of file
+export default GuardrailsPanel
diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsx
index cc20c231bbb..36de2166a36 100644
--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsx
+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_info.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from "react";
+import React, { useState, useEffect } from "react"
import {
Card,
Title,
@@ -12,131 +12,131 @@ import {
TabPanel,
TabPanels,
TextInput,
-} from "@tremor/react";
-import { Button, Form, Input, Select, message, Tooltip, Divider } from "antd";
-import { InfoCircleOutlined } from '@ant-design/icons';
-import { getGuardrailInfo, updateGuardrailCall, getGuardrailUISettings, getGuardrailProviderSpecificParams } from "@/components/networking";
-import { getGuardrailLogoAndName, guardrail_provider_map } from "./guardrail_info_helpers";
-import PiiConfiguration from "./pii_configuration";
-import GuardrailProviderFields from "./guardrail_provider_fields";
-import GuardrailOptionalParams from "./guardrail_optional_params";
+} from "@tremor/react"
+import { Button, Form, Input, Select, message, Tooltip, Divider } from "antd"
+import { InfoCircleOutlined } from "@ant-design/icons"
+import {
+ getGuardrailInfo,
+ updateGuardrailCall,
+ getGuardrailUISettings,
+ getGuardrailProviderSpecificParams,
+} from "@/components/networking"
+import { getGuardrailLogoAndName, guardrail_provider_map } from "./guardrail_info_helpers"
+import PiiConfiguration from "./pii_configuration"
+import GuardrailProviderFields from "./guardrail_provider_fields"
+import GuardrailOptionalParams from "./guardrail_optional_params"
+import { ArrowLeftIcon } from "@heroicons/react/outline"
export interface GuardrailInfoProps {
- guardrailId: string;
- onClose: () => void;
- accessToken: string | null;
- isAdmin: boolean;
+ guardrailId: string
+ onClose: () => void
+ accessToken: string | null
+ isAdmin: boolean
}
interface ProviderParam {
- param: string;
- description: string;
- required: boolean;
- default_value?: string;
- options?: string[];
- type?: string;
- fields?: { [key: string]: ProviderParam };
- dict_key_options?: string[];
- dict_value_type?: string;
+ param: string
+ description: string
+ required: boolean
+ default_value?: string
+ options?: string[]
+ type?: string
+ fields?: { [key: string]: ProviderParam }
+ dict_key_options?: string[]
+ dict_value_type?: string
}
interface ProviderParamsResponse {
- [provider: string]: { [key: string]: ProviderParam };
+ [provider: string]: { [key: string]: ProviderParam }
}
-const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
- guardrailId,
- onClose,
- accessToken,
- isAdmin
-}) => {
- const [guardrailData, setGuardrailData] = useState<any>(null);
- const [guardrailProviderSpecificParams, setGuardrailProviderSpecificParams] = useState<any>(null);
- const [loading, setLoading] = useState(true);
- const [isEditing, setIsEditing] = useState(false);
- const [form] = Form.useForm();
- const [selectedPiiEntities, setSelectedPiiEntities] = useState<string[]>([]);
- const [selectedPiiActions, setSelectedPiiActions] = useState<{[key: string]: string}>({});
+const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({ guardrailId, onClose, accessToken, isAdmin }) => {
+ const [guardrailData, setGuardrailData] = useState<any>(null)
+ const [guardrailProviderSpecificParams, setGuardrailProviderSpecificParams] = useState<any>(null)
+ const [loading, setLoading] = useState(true)
+ const [isEditing, setIsEditing] = useState(false)
+ const [form] = Form.useForm()
+ const [selectedPiiEntities, setSelectedPiiEntities] = useState<string[]>([])
+ const [selectedPiiActions, setSelectedPiiActions] = useState<{ [key: string]: string }>({})
const [guardrailSettings, setGuardrailSettings] = useState<{
- supported_entities: string[];
- supported_actions: string[];
+ supported_entities: string[]
+ supported_actions: string[]
pii_entity_categories: Array<{
- category: string;
- entities: string[];
- }>;
- supported_modes: string[];
- } | null>(null);
+ category: string
+ entities: string[]
+ }>
+ supported_modes: string[]
+ } | null>(null)
const fetchGuardrailInfo = async () => {
try {
- setLoading(true);
- if (!accessToken) return;
- const response = await getGuardrailInfo(accessToken, guardrailId);
- setGuardrailData(response);
-
+ setLoading(true)
+ if (!accessToken) return
+ const response = await getGuardrailInfo(accessToken, guardrailId)
+ setGuardrailData(response)
+
// Initialize PII configuration from guardrail data
if (response.litellm_params?.pii_entities_config) {
- const piiConfig = response.litellm_params.pii_entities_config;
-
+ const piiConfig = response.litellm_params.pii_entities_config
+
// Clear previous selections
- setSelectedPiiEntities([]);
- setSelectedPiiActions({});
-
+ setSelectedPiiEntities([])
+ setSelectedPiiActions({})
+
// Only if there are entities configured
if (Object.keys(piiConfig).length > 0) {
- const entities: string[] = [];
- const actions: {[key: string]: string} = {};
-
+ const entities: string[] = []
+ const actions: { [key: string]: string } = {}
+
Object.entries(piiConfig).forEach(([entity, action]: [string, any]) => {
- entities.push(entity);
- actions[entity] = typeof action === 'string' ? action : "MASK";
- });
-
- setSelectedPiiEntities(entities);
- setSelectedPiiActions(actions);
+ entities.push(entity)
+ actions[entity] = typeof action === "string" ? action : "MASK"
+ })
+
+ setSelectedPiiEntities(entities)
+ setSelectedPiiActions(actions)
}
} else {
// Clear selections if no PII config exists
- setSelectedPiiEntities([]);
- setSelectedPiiActions({});
+ setSelectedPiiEntities([])
+ setSelectedPiiActions({})
}
} catch (error) {
- message.error("Failed to load guardrail information");
- console.error("Error fetching guardrail info:", error);
+ message.error("Failed to load guardrail information")
+ console.error("Error fetching guardrail info:", error)
} finally {
- setLoading(false);
+ setLoading(false)
}
- };
+ }
const fetchGuardrailProviderSpecificParams = async () => {
try {
- if (!accessToken) return;
- const response = await getGuardrailProviderSpecificParams(accessToken);
- setGuardrailProviderSpecificParams(response);
+ if (!accessToken) return
+ const response = await getGuardrailProviderSpecificParams(accessToken)
+ setGuardrailProviderSpecificParams(response)
} catch (error) {
- console.error("Error fetching guardrail provider specific params:", error);
+ console.error("Error fetching guardrail provider specific params:", error)
}
- };
+ }
const fetchGuardrailUISettings = async () => {
try {
- if (!accessToken) return;
- const uiSettings = await getGuardrailUISettings(accessToken);
- setGuardrailSettings(uiSettings);
-
+ if (!accessToken) return
+ const uiSettings = await getGuardrailUISettings(accessToken)
+ setGuardrailSettings(uiSettings)
} catch (error) {
- console.error("Error fetching guardrail UI settings:", error);
+ console.error("Error fetching guardrail UI settings:", error)
}
- };
+ }
useEffect(() => {
- fetchGuardrailProviderSpecificParams();
- }, [accessToken]);
+ fetchGuardrailProviderSpecificParams()
+ }, [accessToken])
useEffect(() => {
- fetchGuardrailInfo();
- fetchGuardrailUISettings();
- }, [guardrailId, accessToken]);
+ fetchGuardrailInfo()
+ fetchGuardrailUISettings()
+ }, [guardrailId, accessToken])
// Reset form when guardrail data or provider params change
useEffect(() => {
@@ -144,73 +144,71 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
form.setFieldsValue({
guardrail_name: guardrailData.guardrail_name,
...guardrailData.litellm_params,
- guardrail_info: guardrailData.guardrail_info
- ? JSON.stringify(guardrailData.guardrail_info, null, 2)
- : "",
+ guardrail_info: guardrailData.guardrail_info ? JSON.stringify(guardrailData.guardrail_info, null, 2) : "",
// Include any optional_params if they exist
...(guardrailData.litellm_params?.optional_params && {
- optional_params: guardrailData.litellm_params.optional_params
- })
- });
+ optional_params: guardrailData.litellm_params.optional_params,
+ }),
+ })
}
- }, [guardrailData, guardrailProviderSpecificParams, form]);
+ }, [guardrailData, guardrailProviderSpecificParams, form])
const handlePiiEntitySelect = (entity: string) => {
- setSelectedPiiEntities(prev => {
+ setSelectedPiiEntities((prev) => {
if (prev.includes(entity)) {
- return prev.filter(e => e !== entity);
+ return prev.filter((e) => e !== entity)
} else {
- return [...prev, entity];
+ return [...prev, entity]
}
- });
- };
+ })
+ }
const handlePiiActionSelect = (entity: string, action: string) => {
- setSelectedPiiActions(prev => ({
+ setSelectedPiiActions((prev) => ({
...prev,
- [entity]: action
- }));
- };
+ [entity]: action,
+ }))
+ }
const handleGuardrailUpdate = async (values: any) => {
try {
- if (!accessToken) return;
-
+ if (!accessToken) return
+
// Prepare update data object - only include changed fields
const updateData: any = {
- litellm_params: {}
- };
-
+ litellm_params: {},
+ }
+
// Only include guardrail_name if it has changed
if (values.guardrail_name !== guardrailData.guardrail_name) {
- updateData.guardrail_name = values.guardrail_name;
+ updateData.guardrail_name = values.guardrail_name
}
-
+
// Only include default_on if it has changed
if (values.default_on !== guardrailData.litellm_params?.default_on) {
- updateData.litellm_params.default_on = values.default_on;
+ updateData.litellm_params.default_on = values.default_on
}
-
+
// Only include guardrail_info if it has changed
- const originalGuardrailInfo = guardrailData.guardrail_info;
- const newGuardrailInfo = values.guardrail_info ? JSON.parse(values.guardrail_info) : undefined;
+ const originalGuardrailInfo = guardrailData.guardrail_info
+ const newGuardrailInfo = values.guardrail_info ? JSON.parse(values.guardrail_info) : undefined
if (JSON.stringify(originalGuardrailInfo) !== JSON.stringify(newGuardrailInfo)) {
- updateData.guardrail_info = newGuardrailInfo;
+ updateData.guardrail_info = newGuardrailInfo
}
-
+
// Only add PII entities config if there are changes
- const originalPiiConfig = guardrailData.litellm_params?.pii_entities_config || {};
- const newPiiEntitiesConfig: {[key: string]: string} = {};
-
- selectedPiiEntities.forEach(entity => {
- newPiiEntitiesConfig[entity] = selectedPiiActions[entity] || "MASK";
- });
-
+ const originalPiiConfig = guardrailData.litellm_params?.pii_entities_config || {}
+ const newPiiEntitiesConfig: { [key: string]: string } = {}
+
+ selectedPiiEntities.forEach((entity) => {
+ newPiiEntitiesConfig[entity] = selectedPiiActions[entity] || "MASK"
+ })
+
// Only update if PII config has changed
if (JSON.stringify(originalPiiConfig) !== JSON.stringify(newPiiEntitiesConfig)) {
- updateData.litellm_params.pii_entities_config = newPiiEntitiesConfig;
+ updateData.litellm_params.pii_entities_config = newPiiEntitiesConfig
}
-
+
/******************************
* Add provider-specific params (reusing logic from add_guardrail_form.tsx)
* ----------------------------------
@@ -219,114 +217,113 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
* Instead of copying every unknown form field, we fetch the list for
* the selected provider and ONLY pass those recognised params.
******************************/
-
+
// Get the current provider from the guardrail data
const currentProvider = Object.keys(guardrail_provider_map).find(
- key => guardrail_provider_map[key] === guardrailData.litellm_params?.guardrail
- );
-
- console.log("values: ", JSON.stringify(values));
- console.log("currentProvider: ", currentProvider);
-
+ (key) => guardrail_provider_map[key] === guardrailData.litellm_params?.guardrail,
+ )
+
+ console.log("values: ", JSON.stringify(values))
+ console.log("currentProvider: ", currentProvider)
+
// Use pre-fetched provider params to copy recognised params
if (guardrailProviderSpecificParams && currentProvider) {
- const providerKey = guardrail_provider_map[currentProvider]?.toLowerCase();
- const providerSpecificParams = guardrailProviderSpecificParams[providerKey] || {};
-
- const allowedParams = new Set<string>();
+ const providerKey = guardrail_provider_map[currentProvider]?.toLowerCase()
+ const providerSpecificParams = guardrailProviderSpecificParams[providerKey] || {}
+
+ const allowedParams = new Set<string>()
+
+ console.log("providerSpecificParams: ", JSON.stringify(providerSpecificParams))
- console.log("providerSpecificParams: ", JSON.stringify(providerSpecificParams));
-
// Add root-level parameters (like api_key, api_base, api_version)
- Object.keys(providerSpecificParams).forEach(paramName => {
- if (paramName !== 'optional_params') {
- allowedParams.add(paramName);
+ Object.keys(providerSpecificParams).forEach((paramName) => {
+ if (paramName !== "optional_params") {
+ allowedParams.add(paramName)
}
- });
-
+ })
+
// Add nested parameters from optional_params.fields
- if (providerSpecificParams.optional_params &&
- providerSpecificParams.optional_params.fields) {
- Object.keys(providerSpecificParams.optional_params.fields).forEach(paramName => {
- allowedParams.add(paramName);
- });
+ if (providerSpecificParams.optional_params && providerSpecificParams.optional_params.fields) {
+ Object.keys(providerSpecificParams.optional_params.fields).forEach((paramName) => {
+ allowedParams.add(paramName)
+ })
}
- console.log("allowedParams: ", allowedParams);
+ console.log("allowedParams: ", allowedParams)
allowedParams.forEach((paramName) => {
// Check for both direct parameter name and nested optional_params object
- let paramValue = values[paramName];
- if (paramValue === undefined || paramValue === null || paramValue === '') {
- paramValue = values.optional_params?.[paramName];
+ let paramValue = values[paramName]
+ if (paramValue === undefined || paramValue === null || paramValue === "") {
+ paramValue = values.optional_params?.[paramName]
}
-
+
// Get the original value for comparison
- const originalValue = guardrailData.litellm_params?.[paramName];
-
+ const originalValue = guardrailData.litellm_params?.[paramName]
+
// Check if the value has changed from the original
- const hasChanged = JSON.stringify(paramValue) !== JSON.stringify(originalValue);
-
+ const hasChanged = JSON.stringify(paramValue) !== JSON.stringify(originalValue)
+
// Include if value has changed and has a meaningful value, OR if user explicitly cleared a value
if (hasChanged) {
- if (paramValue !== undefined && paramValue !== null && paramValue !== '') {
+ if (paramValue !== undefined && paramValue !== null && paramValue !== "") {
// User set a new value
- updateData.litellm_params[paramName] = paramValue;
- } else if (originalValue !== undefined && originalValue !== null && originalValue !== '') {
+ updateData.litellm_params[paramName] = paramValue
+ } else if (originalValue !== undefined && originalValue !== null && originalValue !== "") {
// User cleared an existing value - set to null to indicate removal
- updateData.litellm_params[paramName] = null;
+ updateData.litellm_params[paramName] = null
}
}
- });
+ })
}
-
+
// Remove empty litellm_params object if no parameters were changed
if (Object.keys(updateData.litellm_params).length === 0) {
- delete updateData.litellm_params;
+ delete updateData.litellm_params
}
-
+
// Only proceed with update if there are actual changes
if (Object.keys(updateData).length === 0) {
- message.info("No changes detected");
- setIsEditing(false);
- return;
+ message.info("No changes detected")
+ setIsEditing(false)
+ return
}
-
- await updateGuardrailCall(accessToken, guardrailId, updateData);
- message.success("Guardrail updated successfully");
- fetchGuardrailInfo();
- setIsEditing(false);
+
+ await updateGuardrailCall(accessToken, guardrailId, updateData)
+ message.success("Guardrail updated successfully")
+ fetchGuardrailInfo()
+ setIsEditing(false)
} catch (error) {
- console.error("Error updating guardrail:", error);
- message.error("Failed to update guardrail");
+ console.error("Error updating guardrail:", error)
+ message.error("Failed to update guardrail")
}
- };
+ }
if (loading) {
- return <div className="p-4">Loading...</div>;
+ return <div className="p-4">Loading...</div>
}
if (!guardrailData) {
- return <div className="p-4">Guardrail not found</div>;
+ return <div className="p-4">Guardrail not found</div>
}
// Format date helper function
const formatDate = (dateString?: string) => {
- if (!dateString) return "-";
- const date = new Date(dateString);
- return date.toLocaleString();
- };
+ if (!dateString) return "-"
+ const date = new Date(dateString)
+ return date.toLocaleString()
+ }
// Format the provider display name and logo
- const { logo, displayName } = getGuardrailLogoAndName(guardrailData.litellm_params?.guardrail || "");
+ const { logo, displayName } = getGuardrailLogoAndName(guardrailData.litellm_params?.guardrail || "")
return (
<div className="p-4">
- <div className="flex justify-between items-center mb-6">
- <div>
- <Button onClick={onClose} className="mb-4">← Back</Button>
- <Title>{guardrailData.guardrail_name || "Unnamed Guardrail"}</Title>
- <Text className="text-gray-500 font-mono">{guardrailData.guardrail_id}</Text>
- </div>
+ <div>
+ <TremorButton icon={ArrowLeftIcon} variant="light" onClick={onClose} className="mb-4">
+ Back to Guardrails
+ </TremorButton>
+ <Title>{guardrailData.guardrail_name || "Unnamed Guardrail"}</Title>
+ <Text className="text-gray-500 font-mono">{guardrailData.guardrail_id}</Text>
</div>
<TabGroup>
@@ -343,13 +340,13 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
<Text>Provider</Text>
<div className="mt-2 flex items-center space-x-2">
{logo && (
- <img
- src={logo}
- alt={`${displayName} logo`}
+ <img
+ src={logo}
+ alt={`${displayName} logo`}
className="w-6 h-6"
onError={(e) => {
// Hide broken image
- (e.target as HTMLImageElement).style.display = 'none';
+ ;(e.target as HTMLImageElement).style.display = "none"
}}
/>
)}
@@ -376,16 +373,17 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
</Card>
</Grid>
- {guardrailData.litellm_params?.pii_entities_config && Object.keys(guardrailData.litellm_params.pii_entities_config).length > 0 && (
- <Card className="mt-6">
- <div className="flex justify-between items-center">
- <Text className="font-medium">PII Protection</Text>
- <Badge color="blue">
- {Object.keys(guardrailData.litellm_params.pii_entities_config).length} PII entities configured
- </Badge>
- </div>
- </Card>
- )}
+ {guardrailData.litellm_params?.pii_entities_config &&
+ Object.keys(guardrailData.litellm_params.pii_entities_config).length > 0 && (
+ <Card className="mt-6">
+ <div className="flex justify-between items-center">
+ <Text className="font-medium">PII Protection</Text>
+ <Badge color="blue">
+ {Object.keys(guardrailData.litellm_params.pii_entities_config).length} PII entities configured
+ </Badge>
+ </div>
+ </Card>
+ )}
{guardrailData.guardrail_info && Object.keys(guardrailData.guardrail_info).length > 0 && (
<Card className="mt-6">
@@ -395,9 +393,7 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
<div key={key} className="flex">
<Text className="font-medium w-1/3">{key}</Text>
<Text className="w-2/3">
- {typeof value === 'object'
- ? JSON.stringify(value, null, 2)
- : String(value)}
+ {typeof value === "object" ? JSON.stringify(value, null, 2) : String(value)}
</Text>
</div>
))}
@@ -412,13 +408,7 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
<Card>
<div className="flex justify-between items-center mb-4">
<Title>Guardrail Settings</Title>
- {!isEditing && (
- <TremorButton
- onClick={() => setIsEditing(true)}
- >
- Edit Settings
- </TremorButton>
- )}
+ {!isEditing && <TremorButton onClick={() => setIsEditing(true)}>Edit Settings</TremorButton>}
</div>
{isEditing ? (
@@ -428,13 +418,13 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
initialValues={{
guardrail_name: guardrailData.guardrail_name,
...guardrailData.litellm_params,
- guardrail_info: guardrailData.guardrail_info
- ? JSON.stringify(guardrailData.guardrail_info, null, 2)
+ guardrail_info: guardrailData.guardrail_info
+ ? JSON.stringify(guardrailData.guardrail_info, null, 2)
: "",
// Include any optional_params if they exist
...(guardrailData.litellm_params?.optional_params && {
- optional_params: guardrailData.litellm_params.optional_params
- })
+ optional_params: guardrailData.litellm_params.optional_params,
+ }),
}}
layout="vertical"
>
@@ -445,86 +435,77 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
>
<TextInput />
</Form.Item>
-
- <Form.Item
- label="Default On"
- name="default_on"
- >
+
+ <Form.Item label="Default On" name="default_on">
<Select>
<Select.Option value={true}>Yes</Select.Option>
<Select.Option value={false}>No</Select.Option>
</Select>
</Form.Item>
-
+
{guardrailData.litellm_params?.guardrail === "presidio" && (
<>
- <Divider orientation="left">PII Protection</Divider>
- <div className="mb-6">
- {guardrailSettings && (
- <PiiConfiguration
- entities={guardrailSettings.supported_entities}
- actions={guardrailSettings.supported_actions}
- selectedEntities={selectedPiiEntities}
- selectedActions={selectedPiiActions}
- onEntitySelect={handlePiiEntitySelect}
- onActionSelect={handlePiiActionSelect}
- entityCategories={guardrailSettings.pii_entity_categories}
- />
- )}
- </div>
+ <Divider orientation="left">PII Protection</Divider>
+ <div className="mb-6">
+ {guardrailSettings && (
+ <PiiConfiguration
+ entities={guardrailSettings.supported_entities}
+ actions={guardrailSettings.supported_actions}
+ selectedEntities={selectedPiiEntities}
+ selectedActions={selectedPiiActions}
+ onEntitySelect={handlePiiEntitySelect}
+ onActionSelect={handlePiiActionSelect}
+ entityCategories={guardrailSettings.pii_entity_categories}
+ />
+ )}
+ </div>
</>
)}
-
+
<Divider orientation="left">Provider Settings</Divider>
-
+
{/* Provider-specific fields */}
- <GuardrailProviderFields
- selectedProvider={Object.keys(guardrail_provider_map).find(
- key => guardrail_provider_map[key] === guardrailData.litellm_params?.guardrail
- ) || null}
- accessToken={accessToken}
+ <GuardrailProviderFields
+ selectedProvider={
+ Object.keys(guardrail_provider_map).find(
+ (key) => guardrail_provider_map[key] === guardrailData.litellm_params?.guardrail,
+ ) || null
+ }
+ accessToken={accessToken}
providerParams={guardrailProviderSpecificParams}
value={guardrailData.litellm_params}
/>
-
+
{/* Optional parameters */}
- {guardrailProviderSpecificParams && (
+ {guardrailProviderSpecificParams &&
(() => {
const currentProvider = Object.keys(guardrail_provider_map).find(
- key => guardrail_provider_map[key] === guardrailData.litellm_params?.guardrail
- );
- if (!currentProvider) return null;
-
- const providerKey = guardrail_provider_map[currentProvider]?.toLowerCase();
- const providerFields = guardrailProviderSpecificParams[providerKey];
-
- if (!providerFields || !providerFields.optional_params) return null;
-
+ (key) => guardrail_provider_map[key] === guardrailData.litellm_params?.guardrail,
+ )
+ if (!currentProvider) return null
+
+ const providerKey = guardrail_provider_map[currentProvider]?.toLowerCase()
+ const providerFields = guardrailProviderSpecificParams[providerKey]
+
+ if (!providerFields || !providerFields.optional_params) return null
+
return (
<GuardrailOptionalParams
optionalParams={providerFields.optional_params}
parentFieldKey="optional_params"
values={guardrailData.litellm_params}
/>
- );
- })()
- )}
-
+ )
+ })()}
+
<Divider orientation="left">Advanced Settings</Divider>
- <Form.Item
- label="Guardrail Information"
- name="guardrail_info"
- >
+ <Form.Item label="Guardrail Information" name="guardrail_info">
<Input.TextArea rows={5} />
</Form.Item>
<div className="flex justify-end gap-2 mt-6">
- <Button onClick={() => setIsEditing(false)}>
- Cancel
- </Button>
- <TremorButton>
- Save Changes
- </TremorButton>
+ <Button onClick={() => setIsEditing(false)}>Cancel</Button>
+ <TremorButton>Save Changes</TremorButton>
</div>
</Form>
) : (
@@ -551,18 +532,20 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
{guardrailData.litellm_params?.default_on ? "Yes" : "No"}
</Badge>
</div>
-
- {guardrailData.litellm_params?.pii_entities_config && Object.keys(guardrailData.litellm_params.pii_entities_config).length > 0 && (
- <div>
- <Text className="font-medium">PII Protection</Text>
- <div className="mt-2">
- <Badge color="blue">
- {Object.keys(guardrailData.litellm_params.pii_entities_config).length} PII entities configured
- </Badge>
+
+ {guardrailData.litellm_params?.pii_entities_config &&
+ Object.keys(guardrailData.litellm_params.pii_entities_config).length > 0 && (
+ <div>
+ <Text className="font-medium">PII Protection</Text>
+ <div className="mt-2">
+ <Badge color="blue">
+ {Object.keys(guardrailData.litellm_params.pii_entities_config).length} PII entities
+ configured
+ </Badge>
+ </div>
</div>
- </div>
- )}
-
+ )}
+
<div>
<Text className="font-medium">Created At</Text>
<div>{formatDate(guardrailData.created_at)}</div>
@@ -579,7 +562,7 @@ const GuardrailInfoView: React.FC<GuardrailInfoProps> = ({
</TabPanels>
</TabGroup>
</div>
- );
-};
+ )
+}
-export default GuardrailInfoView;
\ No newline at end of file
+export default GuardrailInfoView
diff --git a/ui/litellm-dashboard/src/components/guardrails/guardrail_table.tsx b/ui/litellm-dashboard/src/components/guardrails/guardrail_table.tsx
index cf6ccade35d..fad26e033bf 100644
--- a/ui/litellm-dashboard/src/components/guardrails/guardrail_table.tsx
+++ b/ui/litellm-dashboard/src/components/guardrails/guardrail_table.tsx
@@ -1,22 +1,8 @@
-import React, { useState } from "react";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeaderCell,
- TableRow,
- Icon,
- Button,
-} from "@tremor/react";
-import {
- TrashIcon,
- SwitchVerticalIcon,
- ChevronUpIcon,
- ChevronDownIcon,
-} from "@heroicons/react/outline";
-import { Tooltip } from "antd";
-import { Badge } from "@tremor/react";
+import React, { useState } from "react"
+import { Table, TableBody, TableCell, TableHead, TableHeaderCell, TableRow, Icon, Button } from "@tremor/react"
+import { TrashIcon, SwitchVerticalIcon, ChevronUpIcon, ChevronDownIcon } from "@heroicons/react/outline"
+import { Tooltip } from "antd"
+import { Badge } from "@tremor/react"
import {
ColumnDef,
flexRender,
@@ -24,34 +10,33 @@ import {
getSortedRowModel,
SortingState,
useReactTable,
-} from "@tanstack/react-table";
-import { getGuardrailLogoAndName, guardrail_provider_map } from "./guardrail_info_helpers";
-import EditGuardrailForm from "./edit_guardrail_form";
-import GuardrailInfoView from "./guardrail_info";
+} from "@tanstack/react-table"
+import { getGuardrailLogoAndName, guardrail_provider_map } from "./guardrail_info_helpers"
+import EditGuardrailForm from "./edit_guardrail_form"
interface GuardrailItem {
- guardrail_id?: string;
- guardrail_name: string | null;
+ guardrail_id?: string
+ guardrail_name: string | null
litellm_params: {
- guardrail: string;
- mode: string;
- default_on: boolean;
- pii_entities_config?: {[key: string]: string};
- [key: string]: any;
- };
- guardrail_info: Record<string, any> | null;
- created_at?: string;
- updated_at?: string;
+ guardrail: string
+ mode: string
+ default_on: boolean
+ pii_entities_config?: { [key: string]: string }
+ [key: string]: any
+ }
+ guardrail_info: Record<string, any> | null
+ created_at?: string
+ updated_at?: string
}
interface GuardrailTableProps {
- guardrailsList: GuardrailItem[];
- isLoading: boolean;
- onDeleteClick: (guardrailId: string, guardrailName: string) => void;
- accessToken: string | null;
- onGuardrailUpdated: () => void;
- isAdmin?: boolean;
- onShowGuardrailInfo?: (isVisible: boolean) => void;
+ guardrailsList: GuardrailItem[]
+ isLoading: boolean
+ onDeleteClick: (guardrailId: string, guardrailName: string) => void
+ accessToken: string | null
+ onGuardrailUpdated: () => void
+ isAdmin?: boolean
+ onGuardrailClick: (id: string) => void
}
const GuardrailTable: React.FC<GuardrailTableProps> = ({
@@ -61,52 +46,29 @@ const GuardrailTable: React.FC<GuardrailTableProps> = ({
accessToken,
onGuardrailUpdated,
isAdmin = false,
- onShowGuardrailInfo,
+ onGuardrailClick,
}) => {
- const [sorting, setSorting] = useState<SortingState>([
- { id: "created_at", desc: true }
- ]);
- const [editModalVisible, setEditModalVisible] = useState(false);
- const [selectedGuardrail, setSelectedGuardrail] = useState<GuardrailItem | null>(null);
- const [showGuardrailInfo, setShowGuardrailInfo] = useState(false);
- const [selectedGuardrailId, setSelectedGuardrailId] = useState<string | null>(null);
+ const [sorting, setSorting] = useState<SortingState>([{ id: "created_at", desc: true }])
+ const [editModalVisible, setEditModalVisible] = useState(false)
+ const [selectedGuardrail, setSelectedGuardrail] = useState<GuardrailItem | null>(null)
// Format date helper function
const formatDate = (dateString?: string) => {
- if (!dateString) return "-";
- const date = new Date(dateString);
- return date.toLocaleString();
- };
+ if (!dateString) return "-"
+ const date = new Date(dateString)
+ return date.toLocaleString()
+ }
const handleEditClick = (guardrail: GuardrailItem) => {
- setSelectedGuardrail(guardrail);
- setEditModalVisible(true);
- };
+ setSelectedGuardrail(guardrail)
+ setEditModalVisible(true)
+ }
const handleEditSuccess = () => {
- setEditModalVisible(false);
- setSelectedGuardrail(null);
- onGuardrailUpdated();
- };
-
- const handleGuardrailIdClick = (guardrailId: string) => {
- setSelectedGuardrailId(guardrailId);
- setShowGuardrailInfo(true);
- onShowGuardrailInfo?.(true);
- };
-
- const handleGuardrailInfoClose = () => {
- setShowGuardrailInfo(false);
- setSelectedGuardrailId(null);
- onShowGuardrailInfo?.(false);
- };
-
- const handleGuardrailDeleted = () => {
- setShowGuardrailInfo(false);
- setSelectedGuardrailId(null);
- onShowGuardrailInfo?.(false);
- onGuardrailUpdated();
- };
+ setEditModalVisible(false)
+ setSelectedGuardrail(null)
+ onGuardrailUpdated()
+ }
const columns: ColumnDef<GuardrailItem>[] = [
{
@@ -114,11 +76,11 @@ const GuardrailTable: React.FC<GuardrailTableProps> = ({
accessorKey: "guardrail_id",
cell: (info: any) => (
<Tooltip title={String(info.getValue() || "")}>
- <Button
+ <Button
size="xs"
variant="light"
className="font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]"
- onClick={() => info.getValue() && handleGuardrailIdClick(info.getValue())}
+ onClick={() => info.getValue() && onGuardrailClick(info.getValue())}
>
{info.getValue() ? `${String(info.getValue()).slice(0, 7)}...` : ""}
</Button>
@@ -129,115 +91,108 @@ const GuardrailTable: React.FC<GuardrailTableProps> = ({
header: "Name",
accessorKey: "guardrail_name",
cell: ({ row }) => {
- const guardrail = row.original;
+ const guardrail = row.original
return (
<Tooltip title={guardrail.guardrail_name}>
- <span className="text-xs font-medium">
- {guardrail.guardrail_name || "-"}
- </span>
+ <span className="text-xs font-medium">{guardrail.guardrail_name || "-"}</span>
</Tooltip>
- );
+ )
},
},
{
header: "Provider",
accessorKey: "litellm_params.guardrail",
cell: ({ row }) => {
- const guardrail = row.original;
- const { logo, displayName } = getGuardrailLogoAndName(guardrail.litellm_params.guardrail);
+ const guardrail = row.original
+ const { logo, displayName } = getGuardrailLogoAndName(guardrail.litellm_params.guardrail)
return (
<div className="flex items-center space-x-2">
{logo && (
- <img
- src={logo}
- alt={`${displayName} logo`}
+ <img
+ src={logo}
+ alt={`${displayName} logo`}
className="w-4 h-4"
onError={(e) => {
// Hide broken image
- (e.target as HTMLImageElement).style.display = 'none';
+ ;(e.target as HTMLImageElement).style.display = "none"
}}
/>
)}
<span className="text-xs">{displayName}</span>
</div>
- );
+ )
},
},
{
header: "Mode",
accessorKey: "litellm_params.mode",
cell: ({ row }) => {
- const guardrail = row.original;
- return (
- <span className="text-xs">
- {guardrail.litellm_params.mode}
- </span>
- );
+ const guardrail = row.original
+ return <span className="text-xs">{guardrail.litellm_params.mode}</span>
},
},
{
header: "Default On",
accessorKey: "litellm_params.default_on",
cell: ({ row }) => {
- const guardrail = row.original;
+ const guardrail = row.original
return (
- <Badge
+ <Badge
color={guardrail.litellm_params?.default_on ? "green" : "gray"}
className="text-xs font-normal"
size="xs"
>
{guardrail.litellm_params?.default_on ? "Default On" : "Default Off"}
</Badge>
- );
+ )
},
},
{
header: "Created At",
accessorKey: "created_at",
cell: ({ row }) => {
- const guardrail = row.original;
+ const guardrail = row.original
return (
<Tooltip title={guardrail.created_at}>
- <span className="text-xs">
- {formatDate(guardrail.created_at)}
- </span>
+ <span className="text-xs">{formatDate(guardrail.created_at)}</span>
</Tooltip>
- );
+ )
},
},
{
header: "Updated At",
accessorKey: "updated_at",
cell: ({ row }) => {
- const guardrail = row.original;
+ const guardrail = row.original
return (
<Tooltip title={guardrail.updated_at}>
- <span className="text-xs">
- {formatDate(guardrail.updated_at)}
- </span>
+ <span className="text-xs">{formatDate(guardrail.updated_at)}</span>
</Tooltip>
- );
+ )
},
},
{
id: "actions",
header: "",
cell: ({ row }) => {
- const guardrail = row.original;
+ const guardrail = row.original
return (
<div className="flex space-x-2">
<Icon
icon={TrashIcon}
size="sm"
- onClick={() => guardrail.guardrail_id && onDeleteClick(guardrail.guardrail_id, guardrail.guardrail_name || 'Unnamed Guardrail')}
+ onClick={() =>
+ guardrail.guardrail_id &&
+ onDeleteClick(guardrail.guardrail_id, guardrail.guardrail_name || "Unnamed Guardrail")
+ }
className="cursor-pointer hover:text-red-500"
tooltip="Delete guardrail"
/>
</div>
- );
+ )
},
},
- ];
+ ]
const table = useReactTable({
data: guardrailsList,
@@ -249,19 +204,7 @@ const GuardrailTable: React.FC<GuardrailTableProps> = ({
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
enableSorting: true,
- });
-
- // If showing guardrail info, render the GuardrailInfoView
- if (showGuardrailInfo && selectedGuardrailId) {
- return (
- <GuardrailInfoView
- guardrailId={selectedGuardrailId}
- onClose={handleGuardrailInfoClose}
- accessToken={accessToken}
- isAdmin={isAdmin}
- />
- );
- }
+ })
return (
<div className="rounded-lg custom-border relative">
@@ -274,27 +217,20 @@ const GuardrailTable: React.FC<GuardrailTableProps> = ({
<TableHeaderCell
key={header.id}
className={`py-1 h-8 ${
- header.id === 'actions'
- ? 'sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]'
- : ''
+ header.id === "actions" ? "sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]" : ""
}`}
onClick={header.column.getToggleSortingHandler()}
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center">
- {header.isPlaceholder ? null : (
- flexRender(
- header.column.columnDef.header,
- header.getContext()
- )
- )}
+ {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</div>
- {header.id !== 'actions' && (
+ {header.id !== "actions" && (
<div className="w-4">
{header.column.getIsSorted() ? (
{
asc: <ChevronUpIcon className="h-4 w-4 text-blue-500" />,
- desc: <ChevronDownIcon className="h-4 w-4 text-blue-500" />
+ desc: <ChevronDownIcon className="h-4 w-4 text-blue-500" />,
}[header.column.getIsSorted() as string]
) : (
<SwitchVerticalIcon className="h-4 w-4 text-gray-400" />
@@ -323,9 +259,9 @@ const GuardrailTable: React.FC<GuardrailTableProps> = ({
<TableCell
key={cell.id}
className={`py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ${
- cell.column.id === 'actions'
- ? 'sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]'
- : ''
+ cell.column.id === "actions"
+ ? "sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]"
+ : ""
}`}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
@@ -353,21 +289,22 @@ const GuardrailTable: React.FC<GuardrailTableProps> = ({
onClose={() => setEditModalVisible(false)}
accessToken={accessToken}
onSuccess={handleEditSuccess}
- guardrailId={selectedGuardrail.guardrail_id || ''}
+ guardrailId={selectedGuardrail.guardrail_id || ""}
initialValues={{
- guardrail_name: selectedGuardrail.guardrail_name || '',
- provider: Object.keys(guardrail_provider_map).find(
- key => guardrail_provider_map[key] === selectedGuardrail?.litellm_params.guardrail
- ) || '',
+ guardrail_name: selectedGuardrail.guardrail_name || "",
+ provider:
+ Object.keys(guardrail_provider_map).find(
+ (key) => guardrail_provider_map[key] === selectedGuardrail?.litellm_params.guardrail,
+ ) || "",
mode: selectedGuardrail.litellm_params.mode,
default_on: selectedGuardrail.litellm_params.default_on,
pii_entities_config: selectedGuardrail.litellm_params.pii_entities_config,
- ...selectedGuardrail.guardrail_info
+ ...selectedGuardrail.guardrail_info,
}}
/>
)}
</div>
- );
-};
+ )
+}
-export default GuardrailTable;
\ No newline at end of file
+export default GuardrailTable
diff --git a/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx b/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx
index e998b1a0eea..616a62cd1c8 100644
--- a/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx
+++ b/ui/litellm-dashboard/src/components/mcp_tools/create_mcp_server.tsx
@@ -1,88 +1,83 @@
-import React, { useState } from "react";
-import {
- Modal,
- Tooltip,
- Form,
- Select,
- message,
- Button as AntdButton,
- Input,
-} from "antd";
-import { InfoCircleOutlined } from "@ant-design/icons";
-import { Button, TextInput } from "@tremor/react";
-import { createMCPServer } from "../networking";
-import { MCPServer, MCPServerCostInfo } from "./types";
-import MCPServerCostConfig from "./mcp_server_cost_config";
-import MCPConnectionStatus from "./mcp_connection_status";
-import StdioConfiguration from "./StdioConfiguration";
-import { isAdminRole } from "@/utils/roles";
+import React, { useState } from "react"
+import { Modal, Tooltip, Form, Select, message, Button as AntdButton, Input } from "antd"
+import { InfoCircleOutlined } from "@ant-design/icons"
+import { Button, TextInput } from "@tremor/react"
+import { createMCPServer } from "../networking"
+import { MCPServer, MCPServerCostInfo } from "./types"
+import MCPServerCostConfig from "./mcp_server_cost_config"
+import MCPConnectionStatus from "./mcp_connection_status"
+import StdioConfiguration from "./StdioConfiguration"
+import { isAdminRole } from "@/utils/roles"
-
-const asset_logos_folder = '../ui/assets/logos/';
-export const mcpLogoImg = `${asset_logos_folder}mcp_logo.png`;
+const asset_logos_folder = "../ui/assets/logos/"
+export const mcpLogoImg = `${asset_logos_folder}mcp_logo.png`
interface CreateMCPServerProps {
- userRole: string;
- accessToken: string | null;
- onCreateSuccess: (newMcpServer: MCPServer) => void;
+ userRole: string
+ accessToken: string | null
+ onCreateSuccess: (newMcpServer: MCPServer) => void
+ isModalVisible: boolean
+ setModalVisible: (visible: boolean) => void
}
const CreateMCPServer: React.FC<CreateMCPServerProps> = ({
userRole,
accessToken,
onCreateSuccess,
+ isModalVisible,
+ setModalVisible,
}) => {
- const [form] = Form.useForm();
- const [isLoading, setIsLoading] = useState(false);
- const [costConfig, setCostConfig] = useState<MCPServerCostInfo>({});
- const [mcpAccessGroups, setMcpAccessGroups] = useState<string[]>([]);
- const [formValues, setFormValues] = useState<Record<string, any>>({});
- const [tools, setTools] = useState<any[]>([]);
- const [transportType, setTransportType] = useState<string>('sse');
+ const [form] = Form.useForm()
+ const [isLoading, setIsLoading] = useState(false)
+ const [costConfig, setCostConfig] = useState<MCPServerCostInfo>({})
+ const [mcpAccessGroups, setMcpAccessGroups] = useState<string[]>([])
+ const [formValues, setFormValues] = useState<Record<string, any>>({})
+ const [tools, setTools] = useState<any[]>([])
+ const [transportType, setTransportType] = useState<string>("sse")
const handleCreate = async (formValues: Record<string, any>) => {
- setIsLoading(true);
+ setIsLoading(true)
try {
// Transform access groups into objects with name property
-
+
const accessGroups = formValues.mcp_access_groups
// Process stdio configuration if present
- let stdioFields = {};
- if (formValues.stdio_config && transportType === 'stdio') {
+ let stdioFields = {}
+ if (formValues.stdio_config && transportType === "stdio") {
try {
- const stdioConfig = JSON.parse(formValues.stdio_config);
-
+ const stdioConfig = JSON.parse(formValues.stdio_config)
+
// Handle both formats:
// 1. Full mcpServers structure: {"mcpServers": {"server-name": {...}}}
// 2. Direct config: {"command": "...", "args": [...], "env": {...}}
-
- let actualConfig = stdioConfig;
-
+
+ let actualConfig = stdioConfig
+
// If it's the full mcpServers structure, extract the first server config
- if (stdioConfig.mcpServers && typeof stdioConfig.mcpServers === 'object') {
- const serverNames = Object.keys(stdioConfig.mcpServers);
+ if (stdioConfig.mcpServers && typeof stdioConfig.mcpServers === "object") {
+ const serverNames = Object.keys(stdioConfig.mcpServers)
if (serverNames.length > 0) {
- const firstServerName = serverNames[0];
- actualConfig = stdioConfig.mcpServers[firstServerName];
-
+ const firstServerName = serverNames[0]
+ actualConfig = stdioConfig.mcpServers[firstServerName]
+
// If no alias is provided, use the server name from the JSON
if (!formValues.alias) {
- formValues.alias = firstServerName.replace(/-/g, '_'); // Replace hyphens with underscores
+ formValues.alias = firstServerName.replace(/-/g, "_") // Replace hyphens with underscores
}
}
}
-
+
stdioFields = {
command: actualConfig.command,
args: actualConfig.args,
- env: actualConfig.env
- };
-
- console.log('Parsed stdio config:', stdioFields);
+ env: actualConfig.env,
+ }
+
+ console.log("Parsed stdio config:", stdioFields)
} catch (error) {
- message.error("Invalid JSON in stdio configuration");
- return;
+ message.error("Invalid JSON in stdio configuration")
+ return
}
}
@@ -97,305 +92,252 @@ const CreateMCPServer: React.FC<CreateMCPServerProps> = ({
description: formValues.description,
mcp_server_cost_info: Object.keys(costConfig).length > 0 ? costConfig : null,
},
- mcp_access_groups: accessGroups
- };
+ mcp_access_groups: accessGroups,
+ }
- console.log(`Payload: ${JSON.stringify(payload)}`);
+ console.log(`Payload: ${JSON.stringify(payload)}`)
if (accessToken != null) {
- const response = await createMCPServer(
- accessToken,
- payload
- );
+ const response = await createMCPServer(accessToken, payload)
- message.success("MCP Server created successfully");
- form.resetFields();
- setCostConfig({});
- setTools([]);
- setModalVisible(false);
- onCreateSuccess(response);
+ message.success("MCP Server created successfully")
+ form.resetFields()
+ setCostConfig({})
+ setTools([])
+ setModalVisible(false)
+ onCreateSuccess(response)
}
} catch (error) {
- message.error("Error creating MCP Server: " + error, 20);
+ message.error("Error creating MCP Server: " + error, 20)
} finally {
- setIsLoading(false);
+ setIsLoading(false)
}
- };
+ }
// state
- const [isModalVisible, setModalVisible] = useState(false);
-
const handleCancel = () => {
- form.resetFields();
- setCostConfig({});
- setTools([]);
- setModalVisible(false);
- };
+ form.resetFields()
+ setCostConfig({})
+ setTools([])
+ setModalVisible(false)
+ }
const handleTransportChange = (value: string) => {
- setTransportType(value);
+ setTransportType(value)
// Clear fields that are not relevant for the selected transport
- if (value === 'stdio') {
- form.setFieldsValue({ url: undefined, auth_type: undefined });
+ if (value === "stdio") {
+ form.setFieldsValue({ url: undefined, auth_type: undefined })
} else {
- form.setFieldsValue({ command: undefined, args: undefined, env: undefined });
+ form.setFieldsValue({ command: undefined, args: undefined, env: undefined })
}
- };
+ }
// rendering
if (!isAdminRole(userRole)) {
- return null;
+ return null
}
return (
- <div>
- <Button
- className="mx-auto mb-4"
- onClick={() => setModalVisible(true)}
- >
- + Add New MCP Server
- </Button>
+ <Modal
+ title={
+ <div className="flex items-center space-x-3 pb-4 border-b border-gray-100">
+ <img
+ src={mcpLogoImg}
+ alt="MCP Logo"
+ className="w-8 h-8 object-contain"
+ style={{
+ height: "20px",
+ width: "20px",
+ marginRight: "8px",
+ objectFit: "contain",
+ }}
+ />
+ <h2 className="text-xl font-semibold text-gray-900">Add New MCP Server</h2>
+ </div>
+ }
+ open={isModalVisible}
+ width={1000}
+ onCancel={handleCancel}
+ footer={null}
+ className="top-8"
+ styles={{
+ body: { padding: "24px" },
+ header: { padding: "24px 24px 0 24px", border: "none" },
+ }}
+ >
+ <div className="mt-6">
+ <Form
+ form={form}
+ onFinish={handleCreate}
+ onValuesChange={(_, allValues) => setFormValues(allValues)}
+ layout="vertical"
+ className="space-y-6"
+ >
+ <div className="grid grid-cols-1 gap-6">
+ <Form.Item
+ label={
+ <span className="text-sm font-medium text-gray-700 flex items-center">
+ MCP Server Name
+ <Tooltip title="Best practice: Use a descriptive name that indicates the server's purpose (e.g., 'GitHub_MCP', 'Email_Service'). Hyphens '-' are not allowed; use underscores '_' instead.">
+ <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
+ </Tooltip>
+ </span>
+ }
+ name="alias"
+ rules={[
+ { required: false, message: "Please enter a server name" },
+ {
+ validator: (_, value) =>
+ value && value.includes("-")
+ ? Promise.reject("Server name cannot contain '-' (hyphen). Please use '_' (underscore) instead.")
+ : Promise.resolve(),
+ },
+ ]}
+ >
+ <TextInput
+ placeholder="e.g., GitHub_MCP, Zapier_MCP, etc."
+ className="rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"
+ />
+ </Form.Item>
- <Modal
- title={
- <div className="flex items-center space-x-3 pb-4 border-b border-gray-100">
- <img
- src={mcpLogoImg}
- alt="MCP Logo"
- className="w-8 h-8 object-contain"
- style={{
- height: '20px',
- width: '20px',
- marginRight: '8px',
- objectFit: 'contain'
- }}
+ <Form.Item
+ label={<span className="text-sm font-medium text-gray-700">Description</span>}
+ name="description"
+ rules={[
+ {
+ required: false,
+ message: "Please enter a server description",
+ },
+ ]}
+ >
+ <TextInput
+ placeholder="Brief description of what this server does"
+ className="rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"
/>
- <h2 className="text-xl font-semibold text-gray-900">Add New MCP Server</h2>
- </div>
- }
- open={isModalVisible}
- width={1000}
- onCancel={handleCancel}
- footer={null}
- className="top-8"
- styles={{
- body: { padding: '24px' },
- header: { padding: '24px 24px 0 24px', border: 'none' },
- }}
- >
- <div className="mt-6">
- <Form
- form={form}
- onFinish={handleCreate}
- onValuesChange={(_, allValues) => setFormValues(allValues)}
- layout="vertical"
- className="space-y-6"
- >
- <div className="grid grid-cols-1 gap-6">
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700 flex items-center">
- MCP Server Name
- <Tooltip title="Best practice: Use a descriptive name that indicates the server's purpose (e.g., 'GitHub_MCP', 'Email_Service'). Hyphens '-' are not allowed; use underscores '_' instead.">
- <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
- </Tooltip>
- </span>
- }
- name="alias"
- rules={[
- { required: false, message: "Please enter a server name" },
- {
- validator: (_, value) =>
- value && value.includes('-')
- ? Promise.reject("Server name cannot contain '-' (hyphen). Please use '_' (underscore) instead.")
- : Promise.resolve(),
- },
- ]}
+ </Form.Item>
+
+ <Form.Item
+ label={<span className="text-sm font-medium text-gray-700">Transport Type</span>}
+ name="transport"
+ rules={[{ required: true, message: "Please select a transport type" }]}
+ >
+ <Select
+ placeholder="Select transport"
+ className="rounded-lg"
+ size="large"
+ onChange={handleTransportChange}
+ value={transportType}
>
- <TextInput
- placeholder="e.g., GitHub_MCP, Zapier_MCP, etc."
- className="rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"
- />
- </Form.Item>
+ <Select.Option value="http">HTTP</Select.Option>
+ <Select.Option value="sse">Server-Sent Events (SSE)</Select.Option>
+ <Select.Option value="stdio">Standard Input/Output (stdio)</Select.Option>
+ </Select>
+ </Form.Item>
+ {/* URL field - only show for HTTP and SSE */}
+ {transportType !== "stdio" && (
<Form.Item
- label={<span className="text-sm font-medium text-gray-700">Description</span>}
- name="description"
+ label={<span className="text-sm font-medium text-gray-700">MCP Server URL</span>}
+ name="url"
rules={[
- {
- required: false,
- message: "Please enter a server description",
- },
+ { required: true, message: "Please enter a server URL" },
+ { type: "url", message: "Please enter a valid URL" },
]}
>
- <TextInput
- placeholder="Brief description of what this server does"
+ <TextInput
+ placeholder="https://your-mcp-server.com"
className="rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"
/>
</Form.Item>
+ )}
+ {/* Authentication - only show for HTTP and SSE */}
+ {transportType !== "stdio" && (
<Form.Item
- label={
- <span className="text-sm font-medium text-gray-700">
- Transport Type
- </span>
- }
- name="transport"
- rules={[{ required: true, message: "Please select a transport type" }]}
+ label={<span className="text-sm font-medium text-gray-700">Authentication</span>}
+ name="auth_type"
+ rules={[{ required: true, message: "Please select an auth type" }]}
>
- <Select
- placeholder="Select transport"
- className="rounded-lg"
- size="large"
- onChange={handleTransportChange}
- value={transportType}
- >
- <Select.Option value="http">HTTP</Select.Option>
- <Select.Option value="sse">Server-Sent Events (SSE)</Select.Option>
- <Select.Option value="stdio">Standard Input/Output (stdio)</Select.Option>
+ <Select placeholder="Select auth type" className="rounded-lg" size="large">
+ <Select.Option value="none">None</Select.Option>
+ <Select.Option value="api_key">API Key</Select.Option>
+ <Select.Option value="bearer_token">Bearer Token</Select.Option>
+ <Select.Option value="basic">Basic Auth</Select.Option>
</Select>
</Form.Item>
+ )}
- {/* URL field - only show for HTTP and SSE */}
- {transportType !== 'stdio' && (
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700">
- MCP Server URL
- </span>
- }
- name="url"
- rules={[
- { required: true, message: "Please enter a server URL" },
- { type: 'url', message: "Please enter a valid URL" }
- ]}
- >
- <TextInput
- placeholder="https://your-mcp-server.com"
- className="rounded-lg border-gray-300 focus:border-blue-500 focus:ring-blue-500"
- />
- </Form.Item>
- )}
-
- {/* Authentication - only show for HTTP and SSE */}
- {transportType !== 'stdio' && (
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700">
- Authentication
- </span>
- }
- name="auth_type"
- rules={[{ required: true, message: "Please select an auth type" }]}
- >
- <Select
- placeholder="Select auth type"
- className="rounded-lg"
- size="large"
- >
- <Select.Option value="none">None</Select.Option>
- <Select.Option value="api_key">API Key</Select.Option>
- <Select.Option value="bearer_token">Bearer Token</Select.Option>
- <Select.Option value="basic">Basic Auth</Select.Option>
- </Select>
- </Form.Item>
- )}
-
- {/* Stdio Configuration - only show for stdio transport */}
- <StdioConfiguration isVisible={transportType === 'stdio'} />
-
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700 flex items-center">
- MCP Version
- <Tooltip title="Select the MCP specification version your server supports">
- <InfoCircleOutlined className="ml-2 text-gray-400 hover:text-gray-600" />
- </Tooltip>
- </span>
- }
- name="spec_version"
- rules={[
- { required: true, message: "Please select a spec version" },
- ]}
- >
- <Select
- placeholder="Select MCP version"
- className="rounded-lg"
- size="large"
- >
- <Select.Option value="2025-03-26">2025-03-26 (Latest)</Select.Option>
- <Select.Option value="2024-11-05">2024-11-05</Select.Option>
- </Select>
- </Form.Item>
-
- <Form.Item
- label={
- <span className="text-sm font-medium text-gray-700 flex items-center">
- MCP Access Groups
- <Tooltip title="Specify access groups for this MCP server. Users must be in at least one of these groups to access the server.">
- <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
- </Tooltip>
- </span>
- }
- name="mcp_access_groups"
- className="mb-4"
- >
- <Select
- mode="tags"
- showSearch
- placeholder="Select existing groups or type to create new ones"
- optionFilterProp="children"
- tokenSeparators={[',']}
- options={mcpAccessGroups.map((group) => ({
- value: group,
- label: group
- }))}
- maxTagCount="responsive"
- allowClear
- />
- </Form.Item>
- </div>
+ {/* Stdio Configuration - only show for stdio transport */}
+ <StdioConfiguration isVisible={transportType === "stdio"} />
- {/* Connection Status Section */}
- <div className="mt-8 pt-6 border-t border-gray-200">
- <MCPConnectionStatus
- accessToken={accessToken}
- formValues={formValues}
- onToolsLoaded={setTools}
- />
- </div>
+ <Form.Item
+ label={
+ <span className="text-sm font-medium text-gray-700 flex items-center">
+ MCP Version
+ <Tooltip title="Select the MCP specification version your server supports">
+ <InfoCircleOutlined className="ml-2 text-gray-400 hover:text-gray-600" />
+ </Tooltip>
+ </span>
+ }
+ name="spec_version"
+ rules={[{ required: true, message: "Please select a spec version" }]}
+ >
+ <Select placeholder="Select MCP version" className="rounded-lg" size="large">
+ <Select.Option value="2025-03-26">2025-03-26 (Latest)</Select.Option>
+ <Select.Option value="2024-11-05">2024-11-05</Select.Option>
+ </Select>
+ </Form.Item>
- {/* Cost Configuration Section */}
- <div className="mt-6">
- <MCPServerCostConfig
- value={costConfig}
- onChange={setCostConfig}
- tools={tools}
- disabled={false}
+ <Form.Item
+ label={
+ <span className="text-sm font-medium text-gray-700 flex items-center">
+ MCP Access Groups
+ <Tooltip title="Specify access groups for this MCP server. Users must be in at least one of these groups to access the server.">
+ <InfoCircleOutlined className="ml-2 text-blue-400 hover:text-blue-600 cursor-help" />
+ </Tooltip>
+ </span>
+ }
+ name="mcp_access_groups"
+ className="mb-4"
+ >
+ <Select
+ mode="tags"
+ showSearch
+ placeholder="Select existing groups or type to create new ones"
+ optionFilterProp="children"
+ tokenSeparators={[","]}
+ options={mcpAccessGroups.map((group) => ({
+ value: group,
+ label: group,
+ }))}
+ maxTagCount="responsive"
+ allowClear
/>
- </div>
+ </Form.Item>
+ </div>
- <div className="flex items-center justify-end space-x-3 pt-6 border-t border-gray-100">
- <Button
- variant="secondary"
- onClick={handleCancel}
- >
- Cancel
- </Button>
- <Button
- variant="primary"
- loading={isLoading}
- >
- {isLoading ? 'Creating...' : 'Add MCP Server'}
- </Button>
- </div>
- </Form>
- </div>
- </Modal>
+ {/* Connection Status Section */}
+ <div className="mt-8 pt-6 border-t border-gray-200">
+ <MCPConnectionStatus accessToken={accessToken} formValues={formValues} onToolsLoaded={setTools} />
+ </div>
+ {/* Cost Configuration Section */}
+ <div className="mt-6">
+ <MCPServerCostConfig value={costConfig} onChange={setCostConfig} tools={tools} disabled={false} />
+ </div>
- </div>
- );
-};
+ <div className="flex items-center justify-end space-x-3 pt-6 border-t border-gray-100">
+ <Button variant="secondary" onClick={handleCancel}>
+ Cancel
+ </Button>
+ <Button variant="primary" loading={isLoading}>
+ {isLoading ? "Creating..." : "Add MCP Server"}
+ </Button>
+ </div>
+ </Form>
+ </div>
+ </Modal>
+ )
+}
-export default CreateMCPServer;
\ No newline at end of file
+export default CreateMCPServer
diff --git a/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_view.tsx b/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_view.tsx
index d35c22652fa..1249431e471 100644
--- a/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_view.tsx
+++ b/ui/litellm-dashboard/src/components/mcp_tools/mcp_server_view.tsx
@@ -1,34 +1,22 @@
-import React, { useState } from "react";
-import { EyeIcon, EyeOffIcon } from "@heroicons/react/outline";
-import {
- Title,
- Card,
- Button,
- Text,
- Grid,
- TabGroup,
- TabList,
- TabPanel,
- TabPanels,
- Tab,
- Icon,
-} from "@tremor/react";
+import React, { useState } from "react"
+import { ArrowLeftIcon, EyeIcon, EyeOffIcon } from "@heroicons/react/outline"
+import { Title, Card, Button, Text, Grid, TabGroup, TabList, TabPanel, TabPanels, Tab, Icon } from "@tremor/react"
-import { MCPServer, handleTransport, handleAuth } from "./types";
+import { MCPServer, handleTransport, handleAuth } from "./types"
// TODO: Move Tools viewer from index file
-import { MCPToolsViewer } from ".";
-import MCPServerEdit from "./mcp_server_edit";
-import MCPServerCostDisplay from "./mcp_server_cost_display";
-import { getMaskedAndFullUrl } from "./utils";
+import { MCPToolsViewer } from "."
+import MCPServerEdit from "./mcp_server_edit"
+import MCPServerCostDisplay from "./mcp_server_cost_display"
+import { getMaskedAndFullUrl } from "./utils"
interface MCPServerViewProps {
- mcpServer: MCPServer;
- onBack: () => void;
- isProxyAdmin: boolean;
- isEditing: boolean;
- accessToken: string | null;
- userRole: string | null;
- userID: string | null;
+ mcpServer: MCPServer
+ onBack: () => void
+ isProxyAdmin: boolean
+ isEditing: boolean
+ accessToken: string | null
+ userRole: string | null
+ userID: string | null
}
export const MCPServerView: React.FC<MCPServerViewProps> = ({
@@ -40,27 +28,27 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({
userRole,
userID,
}) => {
- const [editing, setEditing] = useState(isEditing);
- const [showFullUrl, setShowFullUrl] = useState(false);
+ const [editing, setEditing] = useState(isEditing)
+ const [showFullUrl, setShowFullUrl] = useState(false)
const handleSuccess = (updated: MCPServer) => {
- setEditing(false);
- onBack();
- };
+ setEditing(false)
+ onBack()
+ }
- const { maskedUrl, hasToken } = getMaskedAndFullUrl(mcpServer.url);
+ const { maskedUrl, hasToken } = getMaskedAndFullUrl(mcpServer.url)
const renderUrlWithToggle = (url: string, showFull: boolean) => {
- if (!hasToken) return url;
- return showFull ? url : maskedUrl;
- };
+ if (!hasToken) return url
+ return showFull ? url : maskedUrl
+ }
return (
<div className="p-4 max-w-full">
<div className="flex justify-between items-center mb-6">
<div>
- <Button onClick={onBack} className="mb-4">
- ← Back
+ <Button icon={ArrowLeftIcon} variant="light" className="mb-4">
+ Back to All Servers
</Button>
<Title>{mcpServer.alias}</Title>
<Text className="text-gray-500 font-mono">{mcpServer.server_id}</Text>
@@ -102,15 +90,8 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({
{renderUrlWithToggle(mcpServer.url, showFullUrl)}
</Text>
{hasToken && (
- <button
- onClick={() => setShowFullUrl(!showFullUrl)}
- className="p-1 hover:bg-gray-100 rounded"
- >
- <Icon
- icon={showFullUrl ? EyeOffIcon : EyeIcon}
- size="sm"
- className="text-gray-500"
- />
+ <button onClick={() => setShowFullUrl(!showFullUrl)} className="p-1 hover:bg-gray-100 rounded">
+ <Icon icon={showFullUrl ? EyeOffIcon : EyeIcon} size="sm" className="text-gray-500" />
</button>
)}
</div>
@@ -120,7 +101,6 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({
<Title>Cost Configuration</Title>
<MCPServerCostDisplay costConfig={mcpServer.mcp_info?.mcp_server_cost_info} />
</Card>
-
</TabPanel>
{/* Tool Panel */}
@@ -167,15 +147,8 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({
<div className="font-mono break-all overflow-wrap-anywhere max-w-full flex items-center gap-2">
{renderUrlWithToggle(mcpServer.url, showFullUrl)}
{hasToken && (
- <button
- onClick={() => setShowFullUrl(!showFullUrl)}
- className="p-1 hover:bg-gray-100 rounded"
- >
- <Icon
- icon={showFullUrl ? EyeOffIcon : EyeIcon}
- size="sm"
- className="text-gray-500"
- />
+ <button onClick={() => setShowFullUrl(!showFullUrl)} className="p-1 hover:bg-gray-100 rounded">
+ <Icon icon={showFullUrl ? EyeOffIcon : EyeIcon} size="sm" className="text-gray-500" />
</button>
)}
</div>
@@ -198,11 +171,8 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({
{mcpServer.mcp_access_groups && mcpServer.mcp_access_groups.length > 0 ? (
<div className="flex flex-wrap gap-2">
{mcpServer.mcp_access_groups.map((group: any, index: number) => (
- <span
- key={index}
- className="px-2 py-1 bg-gray-100 rounded-md text-sm"
- >
- {typeof group === 'string' ? group : group?.name ?? ''}
+ <span key={index} className="px-2 py-1 bg-gray-100 rounded-md text-sm">
+ {typeof group === "string" ? group : group?.name ?? ""}
</span>
))}
</div>
@@ -222,5 +192,5 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({
</TabPanels>
</TabGroup>
</div>
- );
-};
+ )
+}
diff --git a/ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsx b/ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsx
index 669d97b2306..5b135435091 100644
--- a/ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsx
+++ b/ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsx
@@ -1,62 +1,29 @@
-import React, { useState, useEffect } from "react";
-import { useQuery } from "@tanstack/react-query";
-import {
- Modal,
- message,
- Select,
- Tooltip,
-} from "antd";
-import {
- TabPanel,
- TabPanels,
- TabGroup,
- TabList,
- Tab,
-} from "@tremor/react";
-import {
- Grid,
- Col,
- Title,
- Text,
-} from "@tremor/react";
-import { DataTable } from "../view_logs/table";
-import { mcpServerColumns } from "./mcp_server_columns";
-import {
- deleteMCPServer,
- fetchMCPServers,
-} from "../networking";
-import {
- MCPServer,
- MCPServerProps,
- Team,
-} from "./types";
-import { isAdminRole } from "@/utils/roles";
-import { MCPServerView } from "./mcp_server_view";
-import CreateMCPServer from "./create_mcp_server";
-import MCPConnect from "./mcp_connect";
-import { QuestionCircleOutlined } from '@ant-design/icons';
+import React, { useState, useEffect } from "react"
+import { useQuery } from "@tanstack/react-query"
+import { Modal, message, Select, Tooltip } from "antd"
+import { TabPanel, TabPanels, TabGroup, TabList, Tab, Button } from "@tremor/react"
+import { Grid, Col, Title, Text } from "@tremor/react"
+import { DataTable } from "../view_logs/table"
+import { mcpServerColumns } from "./mcp_server_columns"
+import { deleteMCPServer, fetchMCPServers } from "../networking"
+import { MCPServer, MCPServerProps, Team } from "./types"
+import { isAdminRole } from "@/utils/roles"
+import { MCPServerView } from "./mcp_server_view"
+import CreateMCPServer from "./create_mcp_server"
+import MCPConnect from "./mcp_connect"
+import { QuestionCircleOutlined } from "@ant-design/icons"
-const { Option } = Select;
+const { Option } = Select
const DeleteModal: React.FC<{
- isModalOpen: boolean;
- title: string;
- confirmDelete: () => void;
- cancelDelete: () => void;
-}> = ({
- isModalOpen,
- title,
- confirmDelete,
- cancelDelete,
-}) => {
- if (!isModalOpen) return null;
+ isModalOpen: boolean
+ title: string
+ confirmDelete: () => void
+ cancelDelete: () => void
+}> = ({ isModalOpen, title, confirmDelete, cancelDelete }) => {
+ if (!isModalOpen) return null
return (
- <Modal
- open={isModalOpen}
- onOk={confirmDelete}
- okType="danger"
- onCancel={cancelDelete}
- >
+ <Modal open={isModalOpen} onOk={confirmDelete} okType="danger" onCancel={cancelDelete}>
<Grid numItems={1} className="gap-2 w-full">
<Title>{title}</Title>
<Col numColSpan={1}>
@@ -64,14 +31,10 @@ const DeleteModal: React.FC<{
</Col>
</Grid>
</Modal>
- );
-};
+ )
+}
-const MCPServers: React.FC<MCPServerProps> = ({
- accessToken,
- userRole,
- userID,
-}) => {
+const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID }) => {
const {
data: mcpServers,
isLoading: isLoadingServers,
@@ -79,163 +42,156 @@ const MCPServers: React.FC<MCPServerProps> = ({
} = useQuery({
queryKey: ["mcpServers"],
queryFn: () => {
- if (!accessToken) throw new Error("Access Token required");
- return fetchMCPServers(accessToken);
+ if (!accessToken) throw new Error("Access Token required")
+ return fetchMCPServers(accessToken)
},
enabled: !!accessToken,
- }) as { data: MCPServer[]; isLoading: boolean; refetch: () => void };
+ }) as { data: MCPServer[]; isLoading: boolean; refetch: () => void }
// state
- const [serverIdToDelete, setServerToDelete] = useState<string | null>(null);
- const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
- const [selectedServerId, setSelectedServerId] = useState<string | null>(null);
- const [editServer, setEditServer] = useState(false);
- const [selectedTeam, setSelectedTeam] = useState<string>("all");
- const [selectedMcpAccessGroup, setSelectedMcpAccessGroup] = useState<string>("all");
- const [filteredServers, setFilteredServers] = useState<MCPServer[]>([]);
-
+ const [serverIdToDelete, setServerToDelete] = useState<string | null>(null)
+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
+ const [selectedServerId, setSelectedServerId] = useState<string | null>(null)
+ const [editServer, setEditServer] = useState(false)
+ const [selectedTeam, setSelectedTeam] = useState<string>("all")
+ const [selectedMcpAccessGroup, setSelectedMcpAccessGroup] = useState<string>("all")
+ const [filteredServers, setFilteredServers] = useState<MCPServer[]>([])
+ const [isModalVisible, setModalVisible] = useState(false)
// Get unique teams from all servers
const uniqueTeams = React.useMemo(() => {
- if (!mcpServers) return [];
- const teamsSet = new Set<string>();
- const uniqueTeamsArray: Team[] = [];
+ if (!mcpServers) return []
+ const teamsSet = new Set<string>()
+ const uniqueTeamsArray: Team[] = []
mcpServers.forEach((server: MCPServer) => {
if (server.teams) {
server.teams.forEach((team: Team) => {
- const teamKey = team.team_id;
+ const teamKey = team.team_id
if (!teamsSet.has(teamKey)) {
- teamsSet.add(teamKey);
- uniqueTeamsArray.push(team);
+ teamsSet.add(teamKey)
+ uniqueTeamsArray.push(team)
}
- });
+ })
}
- });
- return uniqueTeamsArray;
- }, [mcpServers]);
+ })
+ return uniqueTeamsArray
+ }, [mcpServers])
// Get unique MCP access groups from all servers
const uniqueMcpAccessGroups = React.useMemo(() => {
- if (!mcpServers) return [];
- return Array.from(new Set(
- mcpServers.flatMap(server => server.mcp_access_groups)
- ));
- }, [mcpServers]);
+ if (!mcpServers) return []
+ return Array.from(new Set(mcpServers.flatMap((server) => server.mcp_access_groups)))
+ }, [mcpServers])
// Handle team filter change
const handleTeamChange = (teamId: string) => {
- setSelectedTeam(teamId);
- filterServers(teamId, selectedMcpAccessGroup);
- };
+ setSelectedTeam(teamId)
+ filterServers(teamId, selectedMcpAccessGroup)
+ }
// Handle MCP access group filter change
const handleMcpAccessGroupChange = (group: string) => {
- setSelectedMcpAccessGroup(group);
- filterServers(selectedTeam, group);
- };
+ setSelectedMcpAccessGroup(group)
+ filterServers(selectedTeam, group)
+ }
// Filtering logic for both team and access group
const filterServers = (teamId: string, group: string) => {
- if (!mcpServers) return setFilteredServers([]);
- let filtered = mcpServers;
+ if (!mcpServers) return setFilteredServers([])
+ let filtered = mcpServers
if (teamId === "personal") {
- setFilteredServers([]);
- return;
+ setFilteredServers([])
+ return
}
if (teamId !== "all") {
- filtered = filtered.filter(server =>
- server.teams?.some(team => team.team_id === teamId)
- );
+ filtered = filtered.filter((server) => server.teams?.some((team) => team.team_id === teamId))
}
if (group !== "all") {
- filtered = filtered.filter(server =>
- server.mcp_access_groups?.some((g: any) =>
- typeof g === 'string' ? g === group : g && g.name === group
- )
- );
+ filtered = filtered.filter((server) =>
+ server.mcp_access_groups?.some((g: any) => (typeof g === "string" ? g === group : g && g.name === group)),
+ )
}
- setFilteredServers(filtered);
- };
+ setFilteredServers(filtered)
+ }
// Initial and effect-based filtering
useEffect(() => {
- filterServers(selectedTeam, selectedMcpAccessGroup);
+ filterServers(selectedTeam, selectedMcpAccessGroup)
// eslint-disable-next-line
- }, [mcpServers]);
+ }, [mcpServers])
const columns = React.useMemo(
() =>
mcpServerColumns(
userRole ?? "",
(serverId: string) => {
- setSelectedServerId(serverId);
- setEditServer(false);
+ setSelectedServerId(serverId)
+ setEditServer(false)
},
(serverId: string) => {
- setSelectedServerId(serverId);
- setEditServer(true);
+ setSelectedServerId(serverId)
+ setEditServer(true)
},
- handleDelete
+ handleDelete,
),
- [userRole]
- );
+ [userRole],
+ )
function handleDelete(server_id: string) {
- setServerToDelete(server_id);
- setIsDeleteModalOpen(true);
+ setServerToDelete(server_id)
+ setIsDeleteModalOpen(true)
}
const confirmDelete = async () => {
if (serverIdToDelete == null || accessToken == null) {
- return;
+ return
}
try {
- await deleteMCPServer(accessToken, serverIdToDelete);
- message.success("Deleted MCP Server successfully");
- refetch();
+ await deleteMCPServer(accessToken, serverIdToDelete)
+ message.success("Deleted MCP Server successfully")
+ refetch()
} catch (error) {
- console.error("Error deleting the mcp server:", error);
+ console.error("Error deleting the mcp server:", error)
}
- setIsDeleteModalOpen(false);
- setServerToDelete(null);
- };
+ setIsDeleteModalOpen(false)
+ setServerToDelete(null)
+ }
const cancelDelete = () => {
- setIsDeleteModalOpen(false);
- setServerToDelete(null);
- };
+ setIsDeleteModalOpen(false)
+ setServerToDelete(null)
+ }
+
+ const handleCreateSuccess = (newMcpServer: MCPServer) => {
+ setFilteredServers((prev) => [...prev, newMcpServer])
+ setModalVisible(false)
+ }
if (!accessToken || !userRole || !userID) {
- return (
- <div className="p-6 text-center text-gray-500">
- Missing required authentication parameters.
- </div>
- );
+ return <div className="p-6 text-center text-gray-500">Missing required authentication parameters.</div>
}
- const ServersTab = () => (
+ const ServersTab = () =>
selectedServerId ? (
<MCPServerView
mcpServer={
- filteredServers.find(
- (server: MCPServer) => server.server_id === selectedServerId
- ) || {
- server_id: '',
- alias: '',
- url: '',
- transport: '',
- spec_version: '',
- auth_type: '',
- created_at: '',
- created_by: '',
- updated_at: '',
- updated_by: '',
+ filteredServers.find((server: MCPServer) => server.server_id === selectedServerId) || {
+ server_id: "",
+ alias: "",
+ url: "",
+ transport: "",
+ spec_version: "",
+ auth_type: "",
+ created_at: "",
+ created_by: "",
+ updated_at: "",
+ updated_by: "",
}
}
onBack={() => {
- setEditServer(false);
- setSelectedServerId(null);
- refetch();
+ setEditServer(false)
+ setSelectedServerId(null)
+ refetch()
}}
isProxyAdmin={isAdminRole(userRole)}
isEditing={editServer}
@@ -245,31 +201,12 @@ const MCPServers: React.FC<MCPServerProps> = ({
/>
) : (
<div className="w-full h-full">
- <div className="flex justify-between items-center mb-6 px-6">
- <div>
- <Title>MCP Servers</Title>
- <Text className="text-tremor-content">
- Configure and manage your MCP servers
- </Text>
- </div>
- {isAdminRole(userRole) && (
- <CreateMCPServer
- userRole={userRole}
- accessToken={accessToken}
- onCreateSuccess={refetch}
- />
- )}
- </div>
<div className="w-full px-6">
<div className="flex flex-col space-y-4">
<div className="flex items-center justify-between bg-gray-50 rounded-lg p-4 border-2 border-gray-200">
<div className="flex items-center gap-4">
<Text className="text-lg font-semibold text-gray-900">Current Team:</Text>
- <Select
- value={selectedTeam}
- onChange={handleTeamChange}
- style={{ width: 300 }}
- >
+ <Select value={selectedTeam} onChange={handleTeamChange} style={{ width: 300 }}>
<Option value="all">
<div className="flex items-center gap-2">
<div className="w-2 h-2 bg-blue-500 rounded-full"></div>
@@ -286,9 +223,7 @@ const MCPServers: React.FC<MCPServerProps> = ({
<Option key={team.team_id} value={team.team_id}>
<div className="flex items-center gap-2">
<div className="w-2 h-2 bg-green-500 rounded-full"></div>
- <span className="font-medium">
- {team.team_alias || team.team_id}
- </span>
+ <span className="font-medium">{team.team_alias || team.team_id}</span>
</div>
</Option>
))}
@@ -296,14 +231,10 @@ const MCPServers: React.FC<MCPServerProps> = ({
<Text className="text-lg font-semibold text-gray-900 ml-6">
Access Group:
<Tooltip title="An MCP Access Group is a set of users or teams that have permission to access specific MCP servers. Use access groups to control and organize who can connect to which servers.">
- <QuestionCircleOutlined style={{ marginLeft: 4, color: '#888' }} />
+ <QuestionCircleOutlined style={{ marginLeft: 4, color: "#888" }} />
</Tooltip>
</Text>
- <Select
- value={selectedMcpAccessGroup}
- onChange={handleMcpAccessGroupChange}
- style={{ width: 300 }}
- >
+ <Select value={selectedMcpAccessGroup} onChange={handleMcpAccessGroupChange} style={{ width: 300 }}>
<Option value="all">
<div className="flex items-center gap-2">
<div className="w-2 h-2 bg-blue-500 rounded-full"></div>
@@ -335,18 +266,31 @@ const MCPServers: React.FC<MCPServerProps> = ({
</div>
</div>
)
- );
return (
- <div className="w-full h-full">
+ <div className="w-full h-full p-6">
<DeleteModal
isModalOpen={isDeleteModalOpen}
title="Delete MCP Server"
confirmDelete={confirmDelete}
cancelDelete={cancelDelete}
/>
+ <CreateMCPServer
+ userRole={userRole}
+ accessToken={accessToken}
+ onCreateSuccess={handleCreateSuccess}
+ isModalVisible={isModalVisible}
+ setModalVisible={setModalVisible}
+ />
+ <Title>MCP Servers</Title>
+ <Text className="text-tremor-content mt-2">Configure and manage your MCP servers</Text>
+ {isAdminRole(userRole) && (
+ <Button className="mt-4 mb-4" onClick={() => setModalVisible(true)}>
+ + Add New MCP Server
+ </Button>
+ )}
<TabGroup className="w-full h-full">
- <TabList className="flex justify-between mt-2 w-full items-center px-6">
+ <TabList className="flex justify-between mt-2 w-full items-center">
<div className="flex">
<Tab>All Servers</Tab>
<Tab>Connect</Tab>
@@ -362,7 +306,7 @@ const MCPServers: React.FC<MCPServerProps> = ({
</TabPanels>
</TabGroup>
</div>
- );
-};
+ )
+}
-export default MCPServers;
+export default MCPServers
diff --git a/ui/litellm-dashboard/src/components/model_dashboard.tsx b/ui/litellm-dashboard/src/components/model_dashboard.tsx
index 4ae965484ac..e4d4c386577 100644
--- a/ui/litellm-dashboard/src/components/model_dashboard.tsx
+++ b/ui/litellm-dashboard/src/components/model_dashboard.tsx
@@ -9,50 +9,34 @@ import {
TableHeaderCell,
TableCell,
TableBody,
- Metric,
Text,
Grid,
- Accordion,
- AccordionHeader,
- AccordionBody,
+ Col,
} from "@tremor/react";
-import { CredentialItem, credentialListCall, CredentialsResponse } from "./networking";
+import {
+ CredentialItem,
+ credentialListCall,
+ CredentialsResponse,
+} from "./networking";
-import ConditionalPublicModelName from "./add_model/conditional_public_model_name";
-import LiteLLMModelNameField from "./add_model/litellm_model_name";
-import AdvancedSettings from "./add_model/advanced_settings";
-import ProviderSpecificFields from "./add_model/provider_specific_fields";
import { handleAddModelSubmit } from "./add_model/handle_add_model_submit";
import CredentialsPanel from "@/components/model_add/credentials";
import { getDisplayModelName } from "./view_model/model_name_display";
-import EditModelModal, { handleEditModelSubmit } from "./edit_model/edit_model_modal";
import {
TabPanel,
TabPanels,
TabGroup,
TabList,
Tab,
- TextInput,
Icon,
- DateRangePicker,
-} from "@tremor/react";
-import {
- Select,
- SelectItem,
- MultiSelect,
- MultiSelectItem,
- DateRangePickerValue,
} from "@tremor/react";
+import { Select, SelectItem, DateRangePickerValue } from "@tremor/react";
import UsageDatePicker from "./shared/usage_date_picker";
import {
modelInfoCall,
- userGetRequesedtModelsCall,
- modelCreateCall,
Model,
modelCostMap,
- modelDeleteCall,
healthCheckCall,
- modelUpdateCall,
modelMetricsCall,
streamingModelMetricsCall,
modelExceptionsCall,
@@ -65,51 +49,21 @@ import {
allEndUsersCall,
} from "./networking";
import { BarChart, AreaChart } from "@tremor/react";
-import {
- Button as Button2,
- Modal,
- Popover,
- Form,
- Input,
- Select as AntdSelect,
- InputNumber,
- message,
- Descriptions,
- Tooltip,
- Space,
- Row,
- Col,
- Checkbox,
-} from "antd";
-import { Badge, BadgeDelta, Button } from "@tremor/react";
-import RequestAccess from "./request_model_access";
+import { Popover, Form, InputNumber, message } from "antd";
+import { Button } from "@tremor/react";
import { Typography } from "antd";
-import TextArea from "antd/es/input/TextArea";
-import {
- InformationCircleIcon,
- PencilAltIcon,
- PencilIcon,
- StatusOnlineIcon,
- TrashIcon,
- RefreshIcon,
- CheckCircleIcon,
- XCircleIcon,
- FilterIcon,
- ChevronUpIcon,
- ChevronDownIcon,
- TableIcon,
-} from "@heroicons/react/outline";
-import DeleteModelButton from "./delete_model_button";
-const { Title: Title2, Link } = Typography;
-import { InfoCircleOutlined, UploadOutlined } from "@ant-design/icons";
+import { RefreshIcon, FilterIcon } from "@heroicons/react/outline";
+import { InfoCircleOutlined } from "@ant-design/icons";
import type { UploadProps } from "antd";
-import { Upload } from "antd";
import TimeToFirstToken from "./model_metrics/time_to_first_token";
-import DynamicFields from "./model_add/dynamic_form";
-import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { Team } from "./key_team_helpers/key_list";
import TeamInfoView from "./team/team_info";
-import { Providers, provider_map, providerLogoMap, getProviderLogoAndName, getPlaceholder, getProviderModels } from "./provider_info_helpers";
+import {
+ Providers,
+ provider_map,
+ getPlaceholder,
+ getProviderModels,
+} from "./provider_info_helpers";
import ModelInfoView from "./model_info_view";
import AddModelTab from "./add_model/add_model_tab";
import { ModelDataTable } from "./model_dashboard/table";
@@ -117,7 +71,7 @@ import { columns } from "./model_dashboard/columns";
import HealthCheckComponent from "./model_dashboard/HealthCheckComponent";
import PassThroughSettings from "./pass_through_settings";
import { all_admin_roles } from "@/utils/roles";
-import { Table as TableInstance } from '@tanstack/react-table';
+import { Table as TableInstance } from "@tanstack/react-table";
interface ModelDashboardProps {
accessToken: string | null;
@@ -131,24 +85,15 @@ interface ModelDashboardProps {
teams: Team[] | null;
}
-interface EditModelModalProps {
- visible: boolean;
- onCancel: () => void;
- model: any; // Assuming TeamType is a type representing your team object
- onSubmit: (data: FormData) => void; // Assuming FormData is the type of data to be submitted
-}
-
interface RetryPolicyObject {
[key: string]: { [retryPolicyKey: string]: number } | undefined;
}
-
interface GlobalExceptionActivityData {
sum_num_rate_limit_exceptions: number;
- daily_data: { date: string; num_rate_limit_exceptions: number; }[];
+ daily_data: { date: string; num_rate_limit_exceptions: number }[];
}
-
//["OpenAI", "Azure OpenAI", "Anthropic", "Gemini (Google AI Studio)", "Amazon Bedrock", "OpenAI-Compatible Endpoints (Groq, Together AI, Mistral AI, etc.)"]
interface ProviderFields {
@@ -163,7 +108,6 @@ interface ProviderSettings {
fields: ProviderFields[];
}
-
const retry_policy_map: Record<string, string> = {
"BadRequestError (400)": "BadRequestErrorRetries",
"AuthenticationError (401)": "AuthenticationErrorRetries",
@@ -184,23 +128,21 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
premiumUser,
teams,
}) => {
- const [pendingRequests, setPendingRequests] = useState<any[]>([]);
const [form] = Form.useForm();
const [modelMap, setModelMap] = useState<any>(null);
const [lastRefreshed, setLastRefreshed] = useState("");
-
- const [providerModels, setProviderModels] = useState<Array<string>>([]); // Explicitly typing providerModels as a string array
- const providers = Object.values(Providers).filter((key) =>
- isNaN(Number(key))
- );
+ const [providerModels, setProviderModels] = useState<Array<string>>([]); // Explicitly typing providerModels as a string array
const [providerSettings, setProviderSettings] = useState<ProviderSettings[]>(
[]
);
- const [selectedProvider, setSelectedProvider] = useState<Providers>(Providers.OpenAI);
+ const [selectedProvider, setSelectedProvider] = useState<Providers>(
+ Providers.OpenAI
+ );
const [healthCheckResponse, setHealthCheckResponse] = useState<any>(null);
- const [isHealthCheckLoading, setIsHealthCheckLoading] = useState<boolean>(false);
+ const [isHealthCheckLoading, setIsHealthCheckLoading] =
+ useState<boolean>(false);
const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
const [selectedModel, setSelectedModel] = useState<any>(null);
@@ -210,13 +152,9 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
const [availableModelAccessGroups, setAvailableModelAccessGroups] = useState<
Array<string>
>([]);
- const [availableProviders, setavailableProviders] = useState<
- Array<string>
->([]);
const [selectedModelGroup, setSelectedModelGroup] = useState<string | null>(
null
);
- const [modelLatencyMetrics, setModelLatencyMetrics] = useState<any[]>([]);
const [modelMetrics, setModelMetrics] = useState<any[]>([]);
const [modelMetricsCategories, setModelMetricsCategories] = useState<any[]>(
[]
@@ -226,7 +164,6 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
useState<any[]>([]);
const [modelExceptions, setModelExceptions] = useState<any[]>([]);
const [allExceptions, setAllExceptions] = useState<any[]>([]);
- const [failureTableData, setFailureTableData] = useState<any[]>([]);
const [slowResponsesData, setSlowResponsesData] = useState<any[]>([]);
const [dateValue, setDateValue] = useState<DateRangePickerValue>({
from: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
@@ -237,10 +174,13 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
useState<RetryPolicyObject | null>(null);
const [defaultRetry, setDefaultRetry] = useState<number>(0);
- const [globalExceptionData, setGlobalExceptionData] = useState<GlobalExceptionActivityData>({} as GlobalExceptionActivityData);
- const [globalExceptionPerDeployment, setGlobalExceptionPerDeployment] = useState<any[]>([]);
+ const [globalExceptionData, setGlobalExceptionData] =
+ useState<GlobalExceptionActivityData>({} as GlobalExceptionActivityData);
+ const [globalExceptionPerDeployment, setGlobalExceptionPerDeployment] =
+ useState<any[]>([]);
- const [showAdvancedFilters, setShowAdvancedFilters] = useState<boolean>(false);
+ const [showAdvancedFilters, setShowAdvancedFilters] =
+ useState<boolean>(false);
const [selectedAPIKey, setSelectedAPIKey] = useState<any | null>(null);
const [selectedCustomer, setSelectedCustomer] = useState<any | null>(null);
@@ -249,7 +189,8 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
const [credentialsList, setCredentialsList] = useState<CredentialItem[]>([]);
// Add state for advanced settings visibility
- const [showAdvancedSettings, setShowAdvancedSettings] = useState<boolean>(false);
+ const [showAdvancedSettings, setShowAdvancedSettings] =
+ useState<boolean>(false);
// Add these state variables
const [selectedModelId, setSelectedModelId] = useState<string | null>(null);
@@ -258,12 +199,17 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null);
const [selectedTeam, setSelectedTeam] = useState<string | null>(null);
- const [selectedTeamFilter, setSelectedTeamFilter] = useState<string | null>(null);
- const [selectedModelAccessGroupFilter, setSelectedModelAccessGroupFilter] = useState<string | null>(null);
+ const [selectedTeamFilter, setSelectedTeamFilter] = useState<string | null>(
+ null
+ );
+ const [selectedModelAccessGroupFilter, setSelectedModelAccessGroupFilter] =
+ useState<string | null>(null);
// Add new state for current team and model view mode
- const [currentTeam, setCurrentTeam] = useState<string>('personal'); // 'personal' or team_id
- const [modelViewMode, setModelViewMode] = useState<'current_team' | 'all'>('current_team');
+ const [currentTeam, setCurrentTeam] = useState<string>("personal"); // 'personal' or team_id
+ const [modelViewMode, setModelViewMode] = useState<"current_team" | "all">(
+ "current_team"
+ );
const [showColumnDropdown, setShowColumnDropdown] = useState(false);
@@ -271,8 +217,14 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
const dropdownRef = useRef<HTMLDivElement>(null);
const tableRef = useRef<TableInstance<any>>(null);
+ const [selectedTabIndex, setSelectedTabIndex] = useState(0);
-
+ const handleCreateNewModelClick = () => {
+ if (selectedModelId) {
+ setSelectedModelId(null);
+ }
+ setSelectedTabIndex(1);
+ };
const setProviderModelsFn = (provider: Providers) => {
const _providerModels = getProviderModels(provider, modelMap);
@@ -283,7 +235,7 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
const updateModelMetrics = async (
modelGroup: string | null,
startTime: Date | undefined,
- endTime: Date | undefined,
+ endTime: Date | undefined
) => {
console.log("Updating model metrics for group:", modelGroup);
if (!accessToken || !userID || !userRole || !startTime || !endTime) {
@@ -366,29 +318,26 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
setSlowResponsesData(slowResponses);
-
if (modelGroup) {
const dailyExceptions = await adminGlobalActivityExceptions(
accessToken,
- startTime?.toISOString().split('T')[0],
- endTime?.toISOString().split('T')[0],
- modelGroup,
+ startTime?.toISOString().split("T")[0],
+ endTime?.toISOString().split("T")[0],
+ modelGroup
);
setGlobalExceptionData(dailyExceptions);
- const dailyExceptionsPerDeplyment = await adminGlobalActivityExceptionsPerDeployment(
- accessToken,
- startTime?.toISOString().split('T')[0],
- endTime?.toISOString().split('T')[0],
- modelGroup,
- )
+ const dailyExceptionsPerDeplyment =
+ await adminGlobalActivityExceptionsPerDeployment(
+ accessToken,
+ startTime?.toISOString().split("T")[0],
+ endTime?.toISOString().split("T")[0],
+ modelGroup
+ );
setGlobalExceptionPerDeployment(dailyExceptionsPerDeplyment);
-
}
-
-
} catch (error) {
console.error("Failed to fetch model metrics", error);
}
@@ -396,32 +345,31 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
const fetchCredentials = async (accessToken: string) => {
try {
- const response: CredentialsResponse = await credentialListCall(accessToken);
+ const response: CredentialsResponse =
+ await credentialListCall(accessToken);
console.log(`credentials: ${JSON.stringify(response)}`);
setCredentialsList(response.credentials);
} catch (error) {
- console.error('Error fetching credentials:', error);
+ console.error("Error fetching credentials:", error);
}
};
-
useEffect(() => {
- updateModelMetrics(
- selectedModelGroup,
- dateValue.from,
- dateValue.to
- );
+ updateModelMetrics(selectedModelGroup, dateValue.from, dateValue.to);
}, [selectedAPIKey, selectedCustomer, selectedTeam]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
- if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
+ if (
+ dropdownRef.current &&
+ !dropdownRef.current.contains(event.target as Node)
+ ) {
setIsDropdownOpen(false);
}
};
- document.addEventListener('mousedown', handleClickOutside);
- return () => document.removeEventListener('mousedown', handleClickOutside);
+ document.addEventListener("mousedown", handleClickOutside);
+ return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
function formatCreatedAt(createdAt: string | null) {
@@ -443,7 +391,6 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
setSelectedModel(null);
};
-
const uploadProps: UploadProps = {
name: "file",
accept: ".json",
@@ -452,10 +399,15 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
const reader = new FileReader();
reader.onload = (e) => {
if (e.target) {
- const jsonStr = e.target.result as string;
- console.log(`Resetting vertex_credentials to JSON; jsonStr: ${jsonStr}`);
+ const jsonStr = e.target.result as string;
+ console.log(
+ `Resetting vertex_credentials to JSON; jsonStr: ${jsonStr}`
+ );
form.setFieldsValue({ vertex_credentials: jsonStr });
- console.log("Form values right after setting:", form.getFieldsValue());
+ console.log(
+ "Form values right after setting:",
+ form.getFieldsValue()
+ );
}
};
reader.readAsText(file);
@@ -466,7 +418,7 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
onChange(info) {
console.log("Upload onChange triggered with values:", info);
console.log("Current form values:", form.getFieldsValue());
-
+
if (info.file.status !== "uploading") {
console.log(info.file, info.fileList);
}
@@ -526,8 +478,6 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
setProviderSettings(_providerSettings);
}
-
-
// loop through modelDataResponse and get all`model_name` values
let all_model_groups: Set<string> = new Set();
for (let i = 0; i < modelDataResponse.data.length; i++) {
@@ -626,27 +576,30 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
const dailyExceptions = await adminGlobalActivityExceptions(
accessToken,
- dateValue.from?.toISOString().split('T')[0],
- dateValue.to?.toISOString().split('T')[0],
- _initial_model_group,
+ dateValue.from?.toISOString().split("T")[0],
+ dateValue.to?.toISOString().split("T")[0],
+ _initial_model_group
);
setGlobalExceptionData(dailyExceptions);
- const dailyExceptionsPerDeplyment = await adminGlobalActivityExceptionsPerDeployment(
- accessToken,
- dateValue.from?.toISOString().split('T')[0],
- dateValue.to?.toISOString().split('T')[0],
- _initial_model_group,
- )
+ const dailyExceptionsPerDeplyment =
+ await adminGlobalActivityExceptionsPerDeployment(
+ accessToken,
+ dateValue.from?.toISOString().split("T")[0],
+ dateValue.to?.toISOString().split("T")[0],
+ _initial_model_group
+ );
setGlobalExceptionPerDeployment(dailyExceptionsPerDeplyment);
console.log("dailyExceptions:", dailyExceptions);
- console.log("dailyExceptionsPerDeplyment:", dailyExceptionsPerDeplyment);
+ console.log(
+ "dailyExceptionsPerDeplyment:",
+ dailyExceptionsPerDeplyment
+ );
-
console.log("slowResponses:", slowResponses);
setSlowResponsesData(slowResponses);
@@ -691,7 +644,15 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
}
handleRefreshClick();
- }, [accessToken, token, userRole, userID, modelMap, lastRefreshed, selectedTeam]);
+ }, [
+ accessToken,
+ token,
+ userRole,
+ userID,
+ modelMap,
+ lastRefreshed,
+ selectedTeam,
+ ]);
if (!modelData) {
return <div>Loading...</div>;
@@ -745,12 +706,10 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
provider = custom_llm_provider;
if (!provider) {
provider =
- splitModel.length === 1
- ? getProviderFromModel(litellm_model_name)
- : firstElement;
-
+ splitModel.length === 1
+ ? getProviderFromModel(litellm_model_name)
+ : firstElement;
}
-
} else {
// litellm_model_name is null or undefined, default provider to openai
provider = "-";
@@ -828,133 +787,120 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
}
};
-
-
const FilterByContent = (
- <div >
- <Text className="mb-1">Select API Key Name</Text>
-
- {
- premiumUser ? (
- <div>
- <Select defaultValue="all-keys">
+ <div>
+ <Text className="mb-1">Select API Key Name</Text>
+
+ {premiumUser ? (
+ <div>
+ <Select defaultValue="all-keys">
+ <SelectItem
+ key="all-keys"
+ value="all-keys"
+ onClick={() => {
+ setSelectedAPIKey(null);
+ }}
+ >
+ All Keys
+ </SelectItem>
+ {keys?.map((key: any, index: number) => {
+ if (
+ key &&
+ key["key_alias"] !== null &&
+ key["key_alias"].length > 0
+ ) {
+ return (
<SelectItem
- key="all-keys"
- value="all-keys"
+ key={index}
+ value={String(index)}
onClick={() => {
- setSelectedAPIKey(null);
+ setSelectedAPIKey(key);
}}
>
- All Keys
+ {key["key_alias"]}
</SelectItem>
- {keys?.map((key: any, index: number) => {
- if (
- key &&
- key["key_alias"] !== null &&
- key["key_alias"].length > 0
- ) {
- return (
-
- <SelectItem
- key={index}
- value={String(index)}
- onClick={() => {
- setSelectedAPIKey(key);
- }}
- >
- {key["key_alias"]}
- </SelectItem>
- );
- }
- return null;
- })}
- </Select>
-
- <Text className="mt-1">
- Select Customer Name
- </Text>
-
- <Select defaultValue="all-customers">
+ );
+ }
+ return null;
+ })}
+ </Select>
+
+ <Text className="mt-1">Select Customer Name</Text>
+
+ <Select defaultValue="all-customers">
+ <SelectItem
+ key="all-customers"
+ value="all-customers"
+ onClick={() => {
+ setSelectedCustomer(null);
+ }}
+ >
+ All Customers
+ </SelectItem>
+ {allEndUsers?.map((user: any, index: number) => {
+ return (
<SelectItem
- key="all-customers"
- value="all-customers"
+ key={index}
+ value={user}
onClick={() => {
- setSelectedCustomer(null);
+ setSelectedCustomer(user);
}}
>
- All Customers
+ {user}
</SelectItem>
- {
- allEndUsers?.map((user: any, index: number) => {
- return (
- <SelectItem
- key={index}
- value={user}
- onClick={() => {
- setSelectedCustomer(user);
- }}
- >
- {user}
- </SelectItem>
- );
- })
- }
- </Select>
-
- <Text className="mt-1">
- Select Team
- </Text>
-
- <Select
- className="w-64 relative z-50"
- defaultValue="all"
- value={selectedTeamFilter ?? "all"}
- onValueChange={(value) => setSelectedTeamFilter(value === "all" ? null : value)}
- >
- <SelectItem value="all">All Teams</SelectItem>
- {teams?.filter(team => team.team_id).map((team) => (
- <SelectItem
- key={team.team_id}
- value={team.team_id}
- >
- {team.team_alias
- ? `${team.team_alias} (${team.team_id.slice(0, 8)}...)`
- : `Team ${team.team_id.slice(0, 8)}...`
- }
- </SelectItem>
- ))}
- </Select>
- </div>
- ): (
- <div>
- {/* ... existing non-premium user content ... */}
- <Text className="mt-1">
- Select Team
- </Text>
-
- <Select
- className="w-64 relative z-50"
- defaultValue="all"
- value={selectedTeamFilter ?? "all"}
- onValueChange={(value) => setSelectedTeamFilter(value === "all" ? null : value)}
- >
- <SelectItem value="all">All Teams</SelectItem>
- {teams?.filter(team => team.team_id).map((team) => (
- <SelectItem
- key={team.team_id}
- value={team.team_id}
- >
- {team.team_alias
- ? `${team.team_alias} (${team.team_id.slice(0, 8)}...)`
- : `Team ${team.team_id.slice(0, 8)}...`
- }
- </SelectItem>
- ))}
- </Select>
- </div>
- )
- }
- </div>
+ );
+ })}
+ </Select>
+
+ <Text className="mt-1">Select Team</Text>
+
+ <Select
+ className="w-64 relative z-50"
+ defaultValue="all"
+ value={selectedTeamFilter ?? "all"}
+ onValueChange={(value) =>
+ setSelectedTeamFilter(value === "all" ? null : value)
+ }
+ >
+ <SelectItem value="all">All Teams</SelectItem>
+ {teams
+ ?.filter((team) => team.team_id)
+ .map((team) => (
+ <SelectItem key={team.team_id} value={team.team_id}>
+ {team.team_alias
+ ? `${team.team_alias} (${team.team_id.slice(0, 8)}...)`
+ : `Team ${team.team_id.slice(0, 8)}...`}
+ </SelectItem>
+ ))}
+ </Select>
+ </div>
+ ) : (
+ <div>
+ {/* ... existing non-premium user content ... */}
+ <Text className="mt-1">Select Team</Text>
+
+ <Select
+ className="w-64 relative z-50"
+ defaultValue="all"
+ value={selectedTeamFilter ?? "all"}
+ onValueChange={(value) =>
+ setSelectedTeamFilter(value === "all" ? null : value)
+ }
+ >
+ <SelectItem value="all">All Teams</SelectItem>
+ {teams
+ ?.filter((team) => team.team_id)
+ .map((team) => (
+ <SelectItem key={team.team_id} value={team.team_id}>
+ {team.team_alias
+ ? `${team.team_alias} (${team.team_id.slice(0, 8)}...)`
+ : `Team ${team.team_id.slice(0, 8)}...`}
+ </SelectItem>
+ ))}
+ </Select>
+ </div>
+ )}
+ </div>
);
const customTooltip = (props: any) => {
@@ -1009,7 +955,6 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
);
};
-
const handleOk = () => {
form
.validateFields()
@@ -1039,8 +984,8 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
if (selectedTeamId) {
return (
<div className="w-full h-full">
- <TeamInfoView
- teamId={selectedTeamId}
+ <TeamInfoView
+ teamId={selectedTeamId}
onClose={() => setSelectedTeamId(null)}
accessToken={accessToken}
is_team_admin={userRole === "Admin"}
@@ -1054,674 +999,814 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({
}
return (
- <div style={{ width: "100%", height: "100%" }}>
- {selectedModelId ? (
- <ModelInfoView
- modelId={selectedModelId}
- editModel={true}
- onClose={() => {
- setSelectedModelId(null);
- setEditModel(false);
- }}
- modelData={modelData.data.find((model: any) => model.model_info.id === selectedModelId)}
- accessToken={accessToken}
- userID={userID}
- userRole={userRole}
- setEditModalVisible={setEditModalVisible}
- setSelectedModel={setSelectedModel}
- onModelUpdate={(updatedModel) => {
- // Update the model in the modelData.data array
- const updatedModelData = {
- ...modelData,
- data: modelData.data.map((model: any) =>
- model.model_info.id === updatedModel.model_info.id ? updatedModel : model
- )
- };
- setModelData(updatedModelData);
- // Trigger a refresh to update UI
- handleRefreshClick();
- }}
- modelAccessGroups={availableModelAccessGroups}
- />
- ) : (
- <TabGroup className="gap-2 p-8 h-[75vh] w-full mt-2">
-
- <TabList className="flex justify-between mt-2 w-full items-center">
- <div className="flex">
- {all_admin_roles.includes(userRole) ? <Tab>All Models</Tab> : <Tab>Your Models</Tab>}
- <Tab>Add Model</Tab>
- {all_admin_roles.includes(userRole) && <Tab>LLM Credentials</Tab>}
- {all_admin_roles.includes(userRole) && <Tab>Pass-Through Endpoints</Tab>}
- {all_admin_roles.includes(userRole) && <Tab>
- Health Status
- </Tab>}
- {all_admin_roles.includes(userRole) && <Tab>Model Analytics</Tab>}
- {all_admin_roles.includes(userRole) && <Tab>Model Retry Settings</Tab>}
-
- </div>
+ <div className="w-full mx-4 h-[75vh]">
+ <Grid numItems={1} className="gap-2 p-8 w-full mt-2">
+ <Col numColSpan={1} className="flex flex-col gap-2">
+ {all_admin_roles.includes(userRole || "") && (
+ <Button className="w-fit" onClick={handleCreateNewModelClick}>
+ + Create New Model
+ </Button>
+ )}
+ {selectedModelId ? (
+ <ModelInfoView
+ modelId={selectedModelId}
+ editModel={true}
+ onClose={() => {
+ setSelectedModelId(null);
+ setEditModel(false);
+ }}
+ modelData={modelData.data.find(
+ (model: any) => model.model_info.id === selectedModelId
+ )}
+ accessToken={accessToken}
+ userID={userID}
+ userRole={userRole}
+ setEditModalVisible={setEditModalVisible}
+ setSelectedModel={setSelectedModel}
+ onModelUpdate={(updatedModel) => {
+ // Update the model in the modelData.data array
+ const updatedModelData = {
+ ...modelData,
+ data: modelData.data.map((model: any) =>
+ model.model_info.id === updatedModel.model_info.id
+ ? updatedModel
+ : model
+ ),
+ };
+ setModelData(updatedModelData);
+ // Trigger a refresh to update UI
+ handleRefreshClick();
+ }}
+ modelAccessGroups={availableModelAccessGroups}
+ />
+ ) : (
+ <TabGroup
+ index={selectedTabIndex}
+ onIndexChange={setSelectedTabIndex}
+ className="gap-2 h-[75vh] w-full "
+ >
+ <TabList className="flex justify-between mt-2 w-full items-center">
+ <div className="flex">
+ {all_admin_roles.includes(userRole) ? (
+ <Tab>All Models</Tab>
+ ) : (
+ <Tab>Your Models</Tab>
+ )}
+ <Tab>Add Model</Tab>
+ {all_admin_roles.includes(userRole) && (
+ <Tab>LLM Credentials</Tab>
+ )}
+ {all_admin_roles.includes(userRole) && (
+ <Tab>Pass-Through Endpoints</Tab>
+ )}
+ {all_admin_roles.includes(userRole) && (
+ <Tab>Health Status</Tab>
+ )}
+ {all_admin_roles.includes(userRole) && (
+ <Tab>Model Analytics</Tab>
+ )}
+ {all_admin_roles.includes(userRole) && (
+ <Tab>Model Retry Settings</Tab>
+ )}
+ </div>
- <div className="flex items-center space-x-2">
- {lastRefreshed && <Text>Last Refreshed: {lastRefreshed}</Text>}
- <Icon
- icon={RefreshIcon} // Modify as necessary for correct icon name
- variant="shadow"
- size="xs"
- className="self-center"
- onClick={handleRefreshClick}
- />
- </div>
- </TabList>
- <TabPanels>
- <TabPanel>
- <Grid>
- <div className="flex flex-col space-y-4">
- <div className="flex justify-between items-center mb-4">
- <div>
- <Title>Model Management</Title>
- {!all_admin_roles.includes(userRole) ? (
- <Text className="text-tremor-content">
- Add models for teams you are an admin for.
- </Text>
- ) : (
- <Text className="text-tremor-content">
- Add and manage models for the proxy
- </Text>
- )}
- </div>
- </div>
+ <div className="flex items-center space-x-2">
+ {lastRefreshed && (
+ <Text>Last Refreshed: {lastRefreshed}</Text>
+ )}
+ <Icon
+ icon={RefreshIcon} // Modify as necessary for correct icon name
+ variant="shadow"
+ size="xs"
+ className="self-center"
+ onClick={handleRefreshClick}
+ />
+ </div>
+ </TabList>
+ <TabPanels>
+ <TabPanel>
+ <Grid>
+ <div className="flex flex-col space-y-4">
+ <div className="flex justify-between items-center mb-4">
+ <div>
+ <Title>Model Management</Title>
+ {!all_admin_roles.includes(userRole) ? (
+ <Text className="text-tremor-content">
+ Add models for teams you are an admin for.
+ </Text>
+ ) : (
+ <Text className="text-tremor-content">
+ Add and manage models for the proxy
+ </Text>
+ )}
+ </div>
+ </div>
- <div className="bg-white rounded-lg shadow">
- <div className="border-b px-6 py-4">
- <div className="flex flex-col space-y-4">
- {/* Current Team Selector - Prominent */}
- <div className="flex items-center justify-between bg-gray-50 rounded-lg p-4 border-2 border-gray-200">
- <div>
- <div className="flex items-center gap-4">
- <Text className="text-lg font-semibold text-gray-900">Current Team:</Text>
- <Select
- className="w-80"
- defaultValue="personal"
- value={currentTeam}
- onValueChange={(value) => setCurrentTeam(value)}
- >
- <SelectItem value="personal">
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
- <span className="font-medium">Personal</span>
+ <div className="bg-white rounded-lg shadow">
+ <div className="border-b px-6 py-4">
+ <div className="flex flex-col space-y-4">
+ {/* Current Team Selector - Prominent */}
+ <div className="flex items-center justify-between bg-gray-50 rounded-lg p-4 border-2 border-gray-200">
+ <div>
+ <div className="flex items-center gap-4">
+ <Text className="text-lg font-semibold text-gray-900">
+ Current Team:
+ </Text>
+ <Select
+ className="w-80"
+ defaultValue="personal"
+ value={currentTeam}
+ onValueChange={(value) =>
+ setCurrentTeam(value)
+ }
+ >
+ <SelectItem value="personal">
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
+ <span className="font-medium">
+ Personal
+ </span>
+ </div>
+ </SelectItem>
+ {teams
+ ?.filter((team) => team.team_id)
+ .map((team) => (
+ <SelectItem
+ key={team.team_id}
+ value={team.team_id}
+ >
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 bg-green-500 rounded-full"></div>
+ <span className="font-medium">
+ {team.team_alias
+ ? `${team.team_alias.slice(0, 30)}...`
+ : `Team ${team.team_id.slice(0, 30)}...`}
+ </span>
+ </div>
+ </SelectItem>
+ ))}
+ </Select>
</div>
- </SelectItem>
- {teams?.filter(team => team.team_id).map((team) => (
- <SelectItem
- key={team.team_id}
- value={team.team_id}
- >
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 bg-green-500 rounded-full"></div>
- <span className="font-medium">
- {team.team_alias
- ? `${team.team_alias.slice(0, 30)}...`
- : `Team ${team.team_id.slice(0, 30)}...`
- }
- </span>
+ {modelViewMode === "current_team" && (
+ <div className="flex items-start gap-2 mt-2 bg-gray-50 rounded">
+ <InfoCircleOutlined className="text-gray-400 mt-0.5 flex-shrink-0 text-xs" />
+ <div className="text-xs text-gray-500">
+ {currentTeam === "personal" ? (
+ <span>
+ To access these models: Create a
+ Virtual Key without selecting a team
+ on the{" "}
+ <a
+ href="/?login=success&page=api-keys"
+ className="text-gray-600 hover:text-gray-800 underline"
+ >
+ Virtual Keys page
+ </a>
+ </span>
+ ) : (
+ <span>
+ To access these models: Create a
+ Virtual Key and select Team as &quot;
+ {currentTeam}&quot; on the{" "}
+ <a
+ href="/?login=success&page=api-keys"
+ className="text-gray-600 hover:text-gray-800 underline"
+ >
+ Virtual Keys page
+ </a>
+ </span>
+ )}
+ </div>
</div>
- </SelectItem>
- ))}
- </Select>
- </div>
- {
- modelViewMode === "current_team" && (
-
- <div className="flex items-start gap-2 mt-2 bg-gray-50 rounded">
- <InfoCircleOutlined className="text-gray-400 mt-0.5 flex-shrink-0 text-xs" />
- <div className="text-xs text-gray-500">
- {currentTeam === "personal" ? (
- <span>
- To access these models: Create a Virtual Key without selecting a team on the {" "}
- <a href="/?login=success&page=api-keys" className="text-gray-600 hover:text-gray-800 underline">
- Virtual Keys page
- </a>
- </span>
- ) : (
- <span>
- To access these models: Create a Virtual Key and select Team as &quot;{currentTeam}&quot; on the {" "}
- <a href="/?login=success&page=api-keys" className="text-gray-600 hover:text-gray-800 underline">
- Virtual Keys page
- </a>
- </span>
)}
</div>
+
+ {/* Model View Mode Toggle - Also prominent */}
+ <div className="flex items-center gap-4">
+ <Text className="text-lg font-semibold text-gray-900">
+ View:
+ </Text>
+ <Select
+ className="w-64"
+ defaultValue="current_team"
+ value={modelViewMode}
+ onValueChange={(value) =>
+ setModelViewMode(
+ value as "current_team" | "all"
+ )
+ }
+ >
+ <SelectItem value="current_team">
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 bg-purple-500 rounded-full"></div>
+ <span className="font-medium">
+ Current Team Models
+ </span>
+ </div>
+ </SelectItem>
+ <SelectItem value="all">
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 bg-gray-500 rounded-full"></div>
+ <span className="font-medium">
+ All Available Models
+ </span>
+ </div>
+ </SelectItem>
+ </Select>
+ </div>
</div>
- )
- }
- </div>
-
-
- {/* Model View Mode Toggle - Also prominent */}
- <div className="flex items-center gap-4">
- <Text className="text-lg font-semibold text-gray-900">View:</Text>
- <Select
- className="w-64"
- defaultValue="current_team"
- value={modelViewMode}
- onValueChange={(value) => setModelViewMode(value as 'current_team' | 'all')}
- >
- <SelectItem value="current_team">
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 bg-purple-500 rounded-full"></div>
- <span className="font-medium">Current Team Models</span>
- </div>
- </SelectItem>
- <SelectItem value="all">
+
+ {/* Other Filters */}
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ {/* Model Name Filter */}
<div className="flex items-center gap-2">
- <div className="w-2 h-2 bg-gray-500 rounded-full"></div>
- <span className="font-medium">All Available Models</span>
+ <Text>Filter by Public Model Name:</Text>
+ <Select
+ className="w-64"
+ defaultValue={selectedModelGroup ?? "all"}
+ onValueChange={(value) =>
+ setSelectedModelGroup(
+ value === "all" ? "all" : value
+ )
+ }
+ value={selectedModelGroup ?? "all"}
+ >
+ <SelectItem value="all">
+ All Models
+ </SelectItem>
+ {availableModelGroups.map((group, idx) => (
+ <SelectItem key={idx} value={group}>
+ {group}
+ </SelectItem>
+ ))}
+ </Select>
</div>
- </SelectItem>
- </Select>
- </div>
-
- </div>
-
- {/* Other Filters */}
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-3">
- {/* Model Name Filter */}
- <div className="flex items-center gap-2">
- <Text>Filter by Public Model Name:</Text>
- <Select
- className="w-64"
- defaultValue={selectedModelGroup ?? "all"}
- onValueChange={(value) => setSelectedModelGroup(value === "all" ? "all" : value)}
- value={selectedModelGroup ?? "all"}
- >
- <SelectItem value="all">All Models</SelectItem>
- {availableModelGroups.map((group, idx) => (
- <SelectItem
- key={idx}
- value={group}
+ <div className="flex items-center gap-2">
+ <Text>Filter by Model Access Group:</Text>
+ <Select
+ className="w-64"
+ defaultValue="all"
+ value={
+ selectedModelAccessGroupFilter ?? "all"
+ }
+ onValueChange={(value) =>
+ setSelectedModelAccessGroupFilter(
+ value === "all" ? null : value
+ )
+ }
>
- {group}
- </SelectItem>
- ))}
- </Select>
+ <SelectItem value="all">
+ All Model Access Groups
+ </SelectItem>
+ {availableModelAccessGroups.map(
+ (accessGroup, idx) => (
+ <SelectItem
+ key={idx}
+ value={accessGroup}
+ >
+ {accessGroup}
+ </SelectItem>
+ )
+ )}
+ </Select>
+ </div>
+ </div>
</div>
- <div className="flex items-center gap-2">
- <Text>Filter by Model Access Group:</Text>
- <Select
- className="w-64"
- defaultValue="all"
- value={selectedModelAccessGroupFilter ?? "all"}
- onValueChange={(value) => setSelectedModelAccessGroupFilter(value === "all" ? null : value)}
- >
- <SelectItem value="all">All Model Access Groups</SelectItem>
- {availableModelAccessGroups.map((accessGroup, idx) => (
- <SelectItem
- key={idx}
- value={accessGroup}
- >
- {accessGroup}
- </SelectItem>
- ))}
- </Select>
+ {/* Results Count */}
+ <div className="flex justify-between items-center">
+ <Text className="text-sm text-gray-700">
+ Showing{" "}
+ {modelData && modelData.data.length > 0
+ ? modelData.data.filter((model: any) => {
+ const modelNameMatch =
+ selectedModelGroup === "all" ||
+ model.model_name ===
+ selectedModelGroup ||
+ !selectedModelGroup;
+ const accessGroupMatch =
+ selectedModelAccessGroupFilter ===
+ "all" ||
+ model.model_info[
+ "access_groups"
+ ]?.includes(
+ selectedModelAccessGroupFilter
+ ) ||
+ !selectedModelAccessGroupFilter;
+ let teamAccessMatch = true;
+ if (modelViewMode === "current_team") {
+ if (currentTeam === "personal") {
+ teamAccessMatch =
+ model.model_info?.direct_access ===
+ true;
+ } else {
+ teamAccessMatch =
+ model.model_info?.access_via_team_ids?.includes(
+ currentTeam
+ ) === true;
+ }
+ }
+
+ return (
+ modelNameMatch &&
+ accessGroupMatch &&
+ teamAccessMatch
+ );
+ }).length
+ : 0}{" "}
+ results
+ </Text>
</div>
</div>
-
</div>
- {/* Results Count */}
- <div className="flex justify-between items-center">
- <Text className="text-sm text-gray-700">
- Showing {modelData && modelData.data.length > 0 ?
- modelData.data.filter((model: any) => {
- const modelNameMatch = selectedModelGroup === "all" || model.model_name === selectedModelGroup || !selectedModelGroup;
- const accessGroupMatch = selectedModelAccessGroupFilter === "all" || model.model_info["access_groups"]?.includes(selectedModelAccessGroupFilter) || !selectedModelAccessGroupFilter;
- let teamAccessMatch = true;
- if (modelViewMode === 'current_team') {
- if (currentTeam === 'personal') {
- teamAccessMatch = model.model_info?.direct_access === true;
- } else {
- teamAccessMatch = model.model_info?.access_via_team_ids?.includes(currentTeam) === true;
- }
- }
-
- return modelNameMatch && accessGroupMatch && teamAccessMatch;
- }).length : 0} results
- </Text>
- </div>
+ <ModelDataTable
+ columns={columns(
+ userRole,
+ userID,
+ premiumUser,
+ setSelectedModelId,
+ setSelectedTeamId,
+ getDisplayModelName,
+ handleEditClick,
+ handleRefreshClick,
+ setEditModel,
+ expandedRows,
+ setExpandedRows
+ )}
+ data={modelData.data.filter((model: any) => {
+ // Model name filter
+ const modelNameMatch =
+ selectedModelGroup === "all" ||
+ model.model_name === selectedModelGroup ||
+ !selectedModelGroup;
+
+ // Model access group filter
+ const accessGroupMatch =
+ selectedModelAccessGroupFilter === "all" ||
+ model.model_info["access_groups"]?.includes(
+ selectedModelAccessGroupFilter
+ ) ||
+ !selectedModelAccessGroupFilter;
+
+ // Team access filter based on current team and view mode
+ let teamAccessMatch = true;
+ if (modelViewMode === "current_team") {
+ if (currentTeam === "personal") {
+ // Show only models with direct access
+ teamAccessMatch =
+ model.model_info?.direct_access === true;
+ } else {
+ // Show only models accessible by the current team
+ teamAccessMatch =
+ model.model_info?.access_via_team_ids?.includes(
+ currentTeam
+ ) === true;
+ }
+ }
+ // For 'all' mode, show all models (teamAccessMatch remains true)
+
+ return (
+ modelNameMatch &&
+ accessGroupMatch &&
+ teamAccessMatch
+ );
+ })}
+ isLoading={false}
+ table={tableRef}
+ />
</div>
</div>
-
- <ModelDataTable
- columns={columns(
- userRole,
- userID,
- premiumUser,
- setSelectedModelId,
- setSelectedTeamId,
- getDisplayModelName,
- handleEditClick,
- handleRefreshClick,
- setEditModel,
- expandedRows,
- setExpandedRows,
- )}
- data={modelData.data.filter(
- (model: any) => {
- // Model name filter
- const modelNameMatch = selectedModelGroup === "all" || model.model_name === selectedModelGroup || !selectedModelGroup;
-
- // Model access group filter
- const accessGroupMatch = selectedModelAccessGroupFilter === "all" || model.model_info["access_groups"]?.includes(selectedModelAccessGroupFilter) || !selectedModelAccessGroupFilter;
-
- // Team access filter based on current team and view mode
- let teamAccessMatch = true;
- if (modelViewMode === 'current_team') {
- if (currentTeam === 'personal') {
- // Show only models with direct access
- teamAccessMatch = model.model_info?.direct_access === true;
- } else {
- // Show only models accessible by the current team
- teamAccessMatch = model.model_info?.access_via_team_ids?.includes(currentTeam) === true;
- }
- }
- // For 'all' mode, show all models (teamAccessMatch remains true)
-
- return modelNameMatch && accessGroupMatch && teamAccessMatch;
- }
- )}
- isLoading={false}
- table={tableRef}
- />
- </div>
- </div>
- </Grid>
- </TabPanel>
- <TabPanel className="h-full">
- <AddModelTab
- form={form}
- handleOk={handleOk}
- selectedProvider={selectedProvider}
- setSelectedProvider={setSelectedProvider}
- providerModels={providerModels}
- setProviderModelsFn={setProviderModelsFn}
- getPlaceholder={getPlaceholder}
- uploadProps={uploadProps}
- showAdvancedSettings={showAdvancedSettings}
- setShowAdvancedSettings={setShowAdvancedSettings}
- teams={teams}
- credentials={credentialsList}
- accessToken={accessToken}
- userRole={userRole}
- />
- </TabPanel>
- <TabPanel>
- <CredentialsPanel accessToken={accessToken} uploadProps={uploadProps} credentialList={credentialsList} fetchCredentials={fetchCredentials} />
- </TabPanel>
- <TabPanel>
- <PassThroughSettings
- accessToken={accessToken}
- userRole={userRole}
- userID={userID}
- modelData={modelData}
- />
- </TabPanel>
- <TabPanel>
- <HealthCheckComponent
- accessToken={accessToken}
- modelData={modelData}
- all_models_on_proxy={all_models_on_proxy}
- getDisplayModelName={getDisplayModelName}
- setSelectedModelId={setSelectedModelId}
- />
- </TabPanel>
- <TabPanel>
- <Grid numItems={4} className="mt-2 mb-2">
- <Col>
- <UsageDatePicker
- value={dateValue}
- className="mr-2"
- onValueChange={(value) => {
- setDateValue(value);
- updateModelMetrics(
- selectedModelGroup,
- value.from,
- value.to
- );
- }}
+ </Grid>
+ </TabPanel>
+ <TabPanel className="h-full">
+ <AddModelTab
+ form={form}
+ handleOk={handleOk}
+ selectedProvider={selectedProvider}
+ setSelectedProvider={setSelectedProvider}
+ providerModels={providerModels}
+ setProviderModelsFn={setProviderModelsFn}
+ getPlaceholder={getPlaceholder}
+ uploadProps={uploadProps}
+ showAdvancedSettings={showAdvancedSettings}
+ setShowAdvancedSettings={setShowAdvancedSettings}
+ teams={teams}
+ credentials={credentialsList}
+ accessToken={accessToken}
+ userRole={userRole}
/>
- </Col>
- <Col className="ml-2">
- <Text>Select Model Group</Text>
- <Select
- defaultValue={
- selectedModelGroup
- ? selectedModelGroup
- : availableModelGroups[0]
- }
- value={
- selectedModelGroup
- ? selectedModelGroup
- : availableModelGroups[0]
- }
- >
- {availableModelGroups.map((group, idx) => (
- <SelectItem
- key={idx}
- value={group}
- onClick={() =>
- updateModelMetrics(group, dateValue.from, dateValue.to)
+ </TabPanel>
+ <TabPanel>
+ <CredentialsPanel
+ accessToken={accessToken}
+ uploadProps={uploadProps}
+ credentialList={credentialsList}
+ fetchCredentials={fetchCredentials}
+ />
+ </TabPanel>
+ <TabPanel>
+ <PassThroughSettings
+ accessToken={accessToken}
+ userRole={userRole}
+ userID={userID}
+ modelData={modelData}
+ />
+ </TabPanel>
+ <TabPanel>
+ <HealthCheckComponent
+ accessToken={accessToken}
+ modelData={modelData}
+ all_models_on_proxy={all_models_on_proxy}
+ getDisplayModelName={getDisplayModelName}
+ setSelectedModelId={setSelectedModelId}
+ />
+ </TabPanel>
+ <TabPanel>
+ <Grid numItems={4} className="mt-2 mb-2">
+ <Col>
+ <UsageDatePicker
+ value={dateValue}
+ className="mr-2"
+ onValueChange={(value) => {
+ setDateValue(value);
+ updateModelMetrics(
+ selectedModelGroup,
+ value.from,
+ value.to
+ );
+ }}
+ />
+ </Col>
+ <Col className="ml-2">
+ <Text>Select Model Group</Text>
+ <Select
+ defaultValue={
+ selectedModelGroup
+ ? selectedModelGroup
+ : availableModelGroups[0]
+ }
+ value={
+ selectedModelGroup
+ ? selectedModelGroup
+ : availableModelGroups[0]
}
>
- {group}
- </SelectItem>
- ))}
- </Select>
- </Col>
- <Col>
- <Popover
- trigger="click" content={FilterByContent}
- overlayStyle={{
- width: "20vw"
- }}
- >
- <Button
- icon={FilterIcon}
- size="md"
- variant="secondary"
- className="mt-4 ml-2"
- style={{
- border: "none",
- }}
- onClick={() => setShowAdvancedFilters(true)}
- >
- </Button>
- </Popover>
- </Col>
-
- </Grid>
-
-
- <Grid numItems={2}>
- <Col>
- <Card className="mr-2 max-h-[400px] min-h-[400px]">
- <TabGroup>
- <TabList variant="line" defaultValue="1">
- <Tab value="1">Avg. Latency per Token</Tab>
- <Tab value="2">Time to first token</Tab>
- </TabList>
- <TabPanels>
- <TabPanel>
- <p className="text-gray-500 italic"> (seconds/token)</p>
- <Text className="text-gray-500 italic mt-1 mb-1">
- average Latency for successfull requests divided by
- the total tokens
- </Text>
- {modelMetrics && modelMetricsCategories && (
- <AreaChart
- title="Model Latency"
- className="h-72"
- data={modelMetrics}
- showLegend={false}
- index="date"
- categories={modelMetricsCategories}
- connectNulls={true}
- customTooltip={customTooltip}
- />
- )}
- </TabPanel>
- <TabPanel>
- <TimeToFirstToken
- modelMetrics={streamingModelMetrics}
- modelMetricsCategories={
- streamingModelMetricsCategories
+ {availableModelGroups.map((group, idx) => (
+ <SelectItem
+ key={idx}
+ value={group}
+ onClick={() =>
+ updateModelMetrics(
+ group,
+ dateValue.from,
+ dateValue.to
+ )
}
- customTooltip={customTooltip}
- premiumUser={premiumUser}
- />
- </TabPanel>
- </TabPanels>
- </TabGroup>
- </Card>
- </Col>
- <Col>
- <Card className="ml-2 max-h-[400px] min-h-[400px] overflow-y-auto">
- <Table>
- <TableHead>
- <TableRow>
- <TableHeaderCell>Deployment</TableHeaderCell>
- <TableHeaderCell>Success Responses</TableHeaderCell>
- <TableHeaderCell>
- Slow Responses <p>Success Responses taking 600+s</p>
- </TableHeaderCell>
- </TableRow>
- </TableHead>
- <TableBody>
- {slowResponsesData.map((metric, idx) => (
- <TableRow key={idx}>
- <TableCell>{metric.api_base}</TableCell>
- <TableCell>{metric.total_count}</TableCell>
- <TableCell>{metric.slow_count}</TableCell>
- </TableRow>
+ >
+ {group}
+ </SelectItem>
))}
- </TableBody>
- </Table>
- </Card>
- </Col>
- </Grid>
- <Grid numItems={1} className="gap-2 w-full mt-2">
- <Card>
-
- <Title>All Exceptions for {selectedModelGroup}</Title>
-
- <BarChart
- className="h-60"
- data={modelExceptions}
- index="model"
- categories={allExceptions}
- stack={true}
-
- yAxisWidth={30}
- />
- </Card>
-
- </Grid>
-
-
- <Grid numItems={1} className="gap-2 w-full mt-2">
- <Card>
- <Title>All Up Rate Limit Errors (429) for {selectedModelGroup}</Title>
- <Grid numItems={1}>
- <Col>
- <Subtitle style={{ fontSize: "15px", fontWeight: "normal", color: "#535452"}}>Num Rate Limit Errors { (globalExceptionData.sum_num_rate_limit_exceptions)}</Subtitle>
- <BarChart
- className="h-40"
- data={globalExceptionData.daily_data}
- index="date"
- colors={['rose']}
- categories={['num_rate_limit_exceptions']}
- onValueChange={(v) => console.log(v)}
- />
+ </Select>
</Col>
<Col>
-
-
-
- </Col>
-
+ <Popover
+ trigger="click"
+ content={FilterByContent}
+ overlayStyle={{
+ width: "20vw",
+ }}
+ >
+ <Button
+ icon={FilterIcon}
+ size="md"
+ variant="secondary"
+ className="mt-4 ml-2"
+ style={{
+ border: "none",
+ }}
+ onClick={() => setShowAdvancedFilters(true)}
+ ></Button>
+ </Popover>
+ </Col>
</Grid>
-
- </Card>
+ <Grid numItems={2}>
+ <Col>
+ <Card className="mr-2 max-h-[400px] min-h-[400px]">
+ <TabGroup>
+ <TabList variant="line" defaultValue="1">
+ <Tab value="1">Avg. Latency per Token</Tab>
+ <Tab value="2">Time to first token</Tab>
+ </TabList>
+ <TabPanels>
+ <TabPanel>
+ <p className="text-gray-500 italic">
+ {" "}
+ (seconds/token)
+ </p>
+ <Text className="text-gray-500 italic mt-1 mb-1">
+ average Latency for successfull requests divided
+ by the total tokens
+ </Text>
+ {modelMetrics && modelMetricsCategories && (
+ <AreaChart
+ title="Model Latency"
+ className="h-72"
+ data={modelMetrics}
+ showLegend={false}
+ index="date"
+ categories={modelMetricsCategories}
+ connectNulls={true}
+ customTooltip={customTooltip}
+ />
+ )}
+ </TabPanel>
+ <TabPanel>
+ <TimeToFirstToken
+ modelMetrics={streamingModelMetrics}
+ modelMetricsCategories={
+ streamingModelMetricsCategories
+ }
+ customTooltip={customTooltip}
+ premiumUser={premiumUser}
+ />
+ </TabPanel>
+ </TabPanels>
+ </TabGroup>
+ </Card>
+ </Col>
+ <Col>
+ <Card className="ml-2 max-h-[400px] min-h-[400px] overflow-y-auto">
+ <Table>
+ <TableHead>
+ <TableRow>
+ <TableHeaderCell>Deployment</TableHeaderCell>
+ <TableHeaderCell>
+ Success Responses
+ </TableHeaderCell>
+ <TableHeaderCell>
+ Slow Responses{" "}
+ <p>Success Responses taking 600+s</p>
+ </TableHeaderCell>
+ </TableRow>
+ </TableHead>
+ <TableBody>
+ {slowResponsesData.map((metric, idx) => (
+ <TableRow key={idx}>
+ <TableCell>{metric.api_base}</TableCell>
+ <TableCell>{metric.total_count}</TableCell>
+ <TableCell>{metric.slow_count}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </Card>
+ </Col>
+ </Grid>
+ <Grid numItems={1} className="gap-2 w-full mt-2">
+ <Card>
+ <Title>All Exceptions for {selectedModelGroup}</Title>
+
+ <BarChart
+ className="h-60"
+ data={modelExceptions}
+ index="model"
+ categories={allExceptions}
+ stack={true}
+ yAxisWidth={30}
+ />
+ </Card>
+ </Grid>
- {
- premiumUser ? (
- <>
- {globalExceptionPerDeployment.map((globalActivity, index) => (
- <Card key={index}>
- <Title>{globalActivity.api_base ? globalActivity.api_base : "Unknown API Base"}</Title>
+ <Grid numItems={1} className="gap-2 w-full mt-2">
+ <Card>
+ <Title>
+ All Up Rate Limit Errors (429) for {selectedModelGroup}
+ </Title>
<Grid numItems={1}>
<Col>
- <Subtitle style={{ fontSize: "15px", fontWeight: "normal", color: "#535452"}}>Num Rate Limit Errors (429) {(globalActivity.sum_num_rate_limit_exceptions)}</Subtitle>
+ <Subtitle
+ style={{
+ fontSize: "15px",
+ fontWeight: "normal",
+ color: "#535452",
+ }}
+ >
+ Num Rate Limit Errors{" "}
+ {globalExceptionData.sum_num_rate_limit_exceptions}
+ </Subtitle>
<BarChart
className="h-40"
- data={globalActivity.daily_data}
+ data={globalExceptionData.daily_data}
index="date"
- colors={['rose']}
- categories={['num_rate_limit_exceptions']}
-
+ colors={["rose"]}
+ categories={["num_rate_limit_exceptions"]}
onValueChange={(v) => console.log(v)}
/>
-
</Col>
+ <Col></Col>
</Grid>
</Card>
- ))}
- </>
- ) :
- <>
- {globalExceptionPerDeployment && globalExceptionPerDeployment.length > 0 &&
- globalExceptionPerDeployment.slice(0, 1).map((globalActivity, index) => (
- <Card key={index}>
- <Title>✨ Rate Limit Errors by Deployment</Title>
- <p className="mb-2 text-gray-500 italic text-[12px]">Upgrade to see exceptions for all deployments</p>
- <Button variant="primary" className="mb-2">
- <a href="https://forms.gle/W3U4PZpJGFHWtHyA9" target="_blank">
- Get Free Trial
- </a>
- </Button>
- <Card>
- <Title>{globalActivity.api_base}</Title>
- <Grid numItems={1}>
- <Col>
- <Subtitle
- style={{
- fontSize: "15px",
- fontWeight: "normal",
- color: "#535452",
- }}
- >
- Num Rate Limit Errors {(globalActivity.sum_num_rate_limit_exceptions)}
- </Subtitle>
- <BarChart
- className="h-40"
- data={globalActivity.daily_data}
- index="date"
- colors={['rose']}
- categories={['num_rate_limit_exceptions']}
-
- onValueChange={(v) => console.log(v)}
- />
- </Col>
-
-
- </Grid>
- </Card>
- </Card>
- ))}
- </>
- }
- </Grid>
-
- </TabPanel>
- <TabPanel>
- <div className="flex items-center">
- <Text>Filter by Public Model Name</Text>
-
- <Select
- className="mb-4 mt-2 ml-2 w-50"
- defaultValue={
- selectedModelGroup
- ? selectedModelGroup
- : availableModelGroups[0]
- }
- value={
- selectedModelGroup
- ? selectedModelGroup
- : availableModelGroups[0]
- }
- onValueChange={(value) => setSelectedModelGroup(value)}
- >
- {availableModelGroups.map((group, idx) => (
- <SelectItem
- key={idx}
- value={group}
- onClick={() => setSelectedModelGroup(group)}
- >
- {group}
- </SelectItem>
- ))}
- </Select>
- </div>
-
- <Title>Retry Policy for {selectedModelGroup}</Title>
- <Text className="mb-6">
- How many retries should be attempted based on the Exception
- </Text>
- {retry_policy_map && (
- <table>
- <tbody>
- {Object.entries(retry_policy_map).map(
- ([exceptionType, retryPolicyKey], idx) => {
- let retryCount =
- modelGroupRetryPolicy?.[selectedModelGroup!]?.[
- retryPolicyKey
- ];
- if (retryCount == null) {
- retryCount = defaultRetry;
- }
- return (
- <tr
- key={idx}
- className="flex justify-between items-center mt-2"
- >
- <td>
- <Text>{exceptionType}</Text>
- </td>
- <td>
- <InputNumber
- className="ml-5"
- value={retryCount}
- min={0}
- step={1}
- onChange={(value) => {
- setModelGroupRetryPolicy(
- (prevModelGroupRetryPolicy) => {
- const prevRetryPolicy =
- prevModelGroupRetryPolicy?.[
- selectedModelGroup!
- ] ?? {};
- return {
- ...(prevModelGroupRetryPolicy ?? {}),
- [selectedModelGroup!]: {
- ...prevRetryPolicy,
- [retryPolicyKey!]: value,
- },
- } as RetryPolicyObject;
+ {premiumUser ? (
+ <>
+ {globalExceptionPerDeployment.map(
+ (globalActivity, index) => (
+ <Card key={index}>
+ <Title>
+ {globalActivity.api_base
+ ? globalActivity.api_base
+ : "Unknown API Base"}
+ </Title>
+ <Grid numItems={1}>
+ <Col>
+ <Subtitle
+ style={{
+ fontSize: "15px",
+ fontWeight: "normal",
+ color: "#535452",
+ }}
+ >
+ Num Rate Limit Errors (429){" "}
+ {
+ globalActivity.sum_num_rate_limit_exceptions
}
- );
- }}
- />
- </td>
- </tr>
- );
- }
+ </Subtitle>
+ <BarChart
+ className="h-40"
+ data={globalActivity.daily_data}
+ index="date"
+ colors={["rose"]}
+ categories={["num_rate_limit_exceptions"]}
+ onValueChange={(v) => console.log(v)}
+ />
+ </Col>
+ </Grid>
+ </Card>
+ )
+ )}
+ </>
+ ) : (
+ <>
+ {globalExceptionPerDeployment &&
+ globalExceptionPerDeployment.length > 0 &&
+ globalExceptionPerDeployment
+ .slice(0, 1)
+ .map((globalActivity, index) => (
+ <Card key={index}>
+ <Title>
+ ✨ Rate Limit Errors by Deployment
+ </Title>
+ <p className="mb-2 text-gray-500 italic text-[12px]">
+ Upgrade to see exceptions for all deployments
+ </p>
+ <Button variant="primary" className="mb-2">
+ <a
+ href="https://forms.gle/W3U4PZpJGFHWtHyA9"
+ target="_blank"
+ >
+ Get Free Trial
+ </a>
+ </Button>
+ <Card>
+ <Title>{globalActivity.api_base}</Title>
+ <Grid numItems={1}>
+ <Col>
+ <Subtitle
+ style={{
+ fontSize: "15px",
+ fontWeight: "normal",
+ color: "#535452",
+ }}
+ >
+ Num Rate Limit Errors{" "}
+ {
+ globalActivity.sum_num_rate_limit_exceptions
+ }
+ </Subtitle>
+ <BarChart
+ className="h-40"
+ data={globalActivity.daily_data}
+ index="date"
+ colors={["rose"]}
+ categories={[
+ "num_rate_limit_exceptions",
+ ]}
+ onValueChange={(v) => console.log(v)}
+ />
+ </Col>
+ </Grid>
+ </Card>
+ </Card>
+ ))}
+ </>
)}
- </tbody>
- </table>
- )}
- <Button className="mt-6 mr-8" onClick={handleSaveRetrySettings}>
- Save
- </Button>
- </TabPanel>
-
- </TabPanels>
- </TabGroup>
- )}
+ </Grid>
+ </TabPanel>
+ <TabPanel>
+ <div className="flex items-center">
+ <Text>Filter by Public Model Name</Text>
+
+ <Select
+ className="mb-4 mt-2 ml-2 w-50"
+ defaultValue={
+ selectedModelGroup
+ ? selectedModelGroup
+ : availableModelGroups[0]
+ }
+ value={
+ selectedModelGroup
+ ? selectedModelGroup
+ : availableModelGroups[0]
+ }
+ onValueChange={(value) => setSelectedModelGroup(value)}
+ >
+ {availableModelGroups.map((group, idx) => (
+ <SelectItem
+ key={idx}
+ value={group}
+ onClick={() => setSelectedModelGroup(group)}
+ >
+ {group}
+ </SelectItem>
+ ))}
+ </Select>
+ </div>
- </div>
+ <Title>Retry Policy for {selectedModelGroup}</Title>
+ <Text className="mb-6">
+ How many retries should be attempted based on the Exception
+ </Text>
+ {retry_policy_map && (
+ <table>
+ <tbody>
+ {Object.entries(retry_policy_map).map(
+ ([exceptionType, retryPolicyKey], idx) => {
+ let retryCount =
+ modelGroupRetryPolicy?.[selectedModelGroup!]?.[
+ retryPolicyKey
+ ];
+ if (retryCount == null) {
+ retryCount = defaultRetry;
+ }
+
+ return (
+ <tr
+ key={idx}
+ className="flex justify-between items-center mt-2"
+ >
+ <td>
+ <Text>{exceptionType}</Text>
+ </td>
+ <td>
+ <InputNumber
+ className="ml-5"
+ value={retryCount}
+ min={0}
+ step={1}
+ onChange={(value) => {
+ setModelGroupRetryPolicy(
+ (prevModelGroupRetryPolicy) => {
+ const prevRetryPolicy =
+ prevModelGroupRetryPolicy?.[
+ selectedModelGroup!
+ ] ?? {};
+ return {
+ ...(prevModelGroupRetryPolicy ??
+ {}),
+ [selectedModelGroup!]: {
+ ...prevRetryPolicy,
+ [retryPolicyKey!]: value,
+ },
+ } as RetryPolicyObject;
+ }
+ );
+ }}
+ />
+ </td>
+ </tr>
+ );
+ }
+ )}
+ </tbody>
+ </table>
+ )}
+ <Button
+ className="mt-6 mr-8"
+ onClick={handleSaveRetrySettings}
+ >
+ Save
+ </Button>
+ </TabPanel>
+ </TabPanels>
+ </TabGroup>
+ )}
+ </Col>
+ </Grid>
+ </div>
);
};
diff --git a/ui/litellm-dashboard/src/components/model_info_view.tsx b/ui/litellm-dashboard/src/components/model_info_view.tsx
index 12ee6854a89..cf82d7df0de 100644
--- a/ui/litellm-dashboard/src/components/model_info_view.tsx
+++ b/ui/litellm-dashboard/src/components/model_info_view.tsx
@@ -15,7 +15,16 @@ import {
} from "@tremor/react";
import NumericalInput from "./shared/numerical_input";
import { ArrowLeftIcon, TrashIcon, KeyIcon } from "@heroicons/react/outline";
-import { modelDeleteCall, modelUpdateCall, CredentialItem, credentialGetCall, credentialCreateCall, modelInfoCall, modelInfoV1Call, modelPatchUpdateCall } from "./networking";
+import {
+ modelDeleteCall,
+ modelUpdateCall,
+ CredentialItem,
+ credentialGetCall,
+ credentialCreateCall,
+ modelInfoCall,
+ modelInfoV1Call,
+ modelPatchUpdateCall,
+} from "./networking";
import { Button, Form, Input, InputNumber, message, Select, Modal } from "antd";
import EditModelModal from "./edit_model/edit_model_modal";
import { handleEditModelSubmit } from "./edit_model/edit_model_modal";
@@ -39,10 +48,10 @@ interface ModelInfoViewProps {
modelAccessGroups: string[] | null;
}
-export default function ModelInfoView({
- modelId,
- onClose,
- modelData,
+export default function ModelInfoView({
+ modelId,
+ onClose,
+ modelData,
accessToken,
userID,
userRole,
@@ -50,7 +59,7 @@ export default function ModelInfoView({
setEditModalVisible,
setSelectedModel,
onModelUpdate,
- modelAccessGroups
+ modelAccessGroups,
}: ModelInfoViewProps) {
const [form] = Form.useForm();
const [localModelData, setLocalModelData] = useState<any>(null);
@@ -59,30 +68,40 @@ export default function ModelInfoView({
const [isDirty, setIsDirty] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [isEditing, setIsEditing] = useState(false);
- const [existingCredential, setExistingCredential] = useState<CredentialItem | null>(null);
+ const [existingCredential, setExistingCredential] =
+ useState<CredentialItem | null>(null);
const [showCacheControl, setShowCacheControl] = useState(false);
- const canEditModel = userRole === "Admin" || modelData.model_info.created_by === userID;
+ const canEditModel =
+ userRole === "Admin" || modelData.model_info.created_by === userID;
const isAdmin = userRole === "Admin";
- const usingExistingCredential = modelData.litellm_params?.litellm_credential_name != null && modelData.litellm_params?.litellm_credential_name != undefined;
+ const usingExistingCredential =
+ modelData.litellm_params?.litellm_credential_name != null &&
+ modelData.litellm_params?.litellm_credential_name != undefined;
console.log("usingExistingCredential, ", usingExistingCredential);
- console.log("modelData.litellm_params.litellm_credential_name, ", modelData.litellm_params.litellm_credential_name);
-
+ console.log(
+ "modelData.litellm_params.litellm_credential_name, ",
+ modelData.litellm_params.litellm_credential_name
+ );
useEffect(() => {
const getExistingCredential = async () => {
console.log("accessToken, ", accessToken);
if (!accessToken) return;
if (usingExistingCredential) return;
- let existingCredentialResponse = await credentialGetCall(accessToken, null, modelId);
+ let existingCredentialResponse = await credentialGetCall(
+ accessToken,
+ null,
+ modelId
+ );
console.log("existingCredentialResponse, ", existingCredentialResponse);
setExistingCredential({
credential_name: existingCredentialResponse["credential_name"],
- credential_values: existingCredentialResponse["credential_values"],
- credential_info: existingCredentialResponse["credential_info"]
+ credential_values: existingCredentialResponse["credential_values"],
+ credential_info: existingCredentialResponse["credential_info"],
});
- }
+ };
const getModelInfo = async () => {
if (!accessToken) return;
@@ -90,12 +109,12 @@ export default function ModelInfoView({
console.log("modelInfoResponse, ", modelInfoResponse);
let specificModelData = modelInfoResponse.data[0];
setLocalModelData(specificModelData);
-
+
// Check if cache control is enabled
if (specificModelData?.litellm_params?.cache_control_injection_points) {
setShowCacheControl(true);
}
- }
+ };
getExistingCredential();
getModelInfo();
}, [accessToken, modelId]);
@@ -107,14 +126,17 @@ export default function ModelInfoView({
credential_name: values.credential_name,
model_id: modelId,
credential_info: {
- "custom_llm_provider": localModelData.litellm_params?.custom_llm_provider,
- }
- }
+ custom_llm_provider: localModelData.litellm_params?.custom_llm_provider,
+ },
+ };
message.info("Storing credential..");
- let credentialResponse = await credentialCreateCall(accessToken, credentialItem);
+ let credentialResponse = await credentialCreateCall(
+ accessToken,
+ credentialItem
+ );
console.log("credentialResponse, ", credentialResponse);
message.success("Credential stored successfully");
- }
+ };
const handleModelUpdate = async (values: any) => {
try {
@@ -122,7 +144,7 @@ export default function ModelInfoView({
setIsSaving(true);
console.log("values.model_name, ", values.model_name);
-
+
let updatedLitellmParams = {
...localModelData.litellm_params,
model: values.litellm_model_name,
@@ -137,10 +159,14 @@ export default function ModelInfoView({
input_cost_per_token: values.input_cost / 1_000_000,
output_cost_per_token: values.output_cost / 1_000_000,
};
-
+
// Handle cache control settings
- if (values.cache_control && values.cache_control_injection_points?.length > 0) {
- updatedLitellmParams.cache_control_injection_points = values.cache_control_injection_points;
+ if (
+ values.cache_control &&
+ values.cache_control_injection_points?.length > 0
+ ) {
+ updatedLitellmParams.cache_control_injection_points =
+ values.cache_control_injection_points;
} else {
delete updatedLitellmParams.cache_control_injection_points;
}
@@ -148,35 +174,37 @@ export default function ModelInfoView({
// Parse the model_info from the form values
let updatedModelInfo;
try {
- updatedModelInfo = values.model_info ? JSON.parse(values.model_info) : modelData.model_info;
+ updatedModelInfo = values.model_info
+ ? JSON.parse(values.model_info)
+ : modelData.model_info;
// Update access_groups from the form
if (values.model_access_group) {
updatedModelInfo = {
...updatedModelInfo,
- access_groups: values.model_access_group
+ access_groups: values.model_access_group,
};
}
} catch (e) {
message.error("Invalid JSON in Model Info");
return;
}
-
+
const updateData = {
model_name: values.model_name,
litellm_params: updatedLitellmParams,
- model_info: updatedModelInfo
+ model_info: updatedModelInfo,
};
await modelPatchUpdateCall(accessToken, updateData, modelId);
-
+
const updatedModelData = {
...localModelData,
model_name: values.model_name,
litellm_model_name: values.litellm_model_name,
litellm_params: updatedLitellmParams,
- model_info: updatedModelInfo
+ model_info: updatedModelInfo,
};
-
+
setLocalModelData(updatedModelData);
if (onModelUpdate) {
@@ -197,13 +225,14 @@ export default function ModelInfoView({
if (!modelData) {
return (
<div className="p-4">
- <Button
- icon={<ArrowLeftIcon />}
+ <TremorButton
+ icon={ArrowLeftIcon}
+ variant="light"
onClick={onClose}
className="mb-4"
>
Back to Models
- </Button>
+ </TremorButton>
<Text>Model not found</Text>
</div>
);
@@ -214,14 +243,14 @@ export default function ModelInfoView({
if (!accessToken) return;
await modelDeleteCall(accessToken, modelId);
message.success("Model deleted successfully");
-
+
if (onModelUpdate) {
- onModelUpdate({
- deleted: true,
- model_info: { id: modelId }
+ onModelUpdate({
+ deleted: true,
+ model_info: { id: modelId },
});
}
-
+
onClose();
} catch (error) {
console.error("Error deleting the model:", error);
@@ -229,20 +258,22 @@ export default function ModelInfoView({
}
};
-
return (
<div className="p-4">
<div className="flex justify-between items-center mb-6">
<div>
- <Button
- icon={<ArrowLeftIcon />}
+ <TremorButton
+ icon={ArrowLeftIcon}
+ variant="light"
onClick={onClose}
className="mb-4"
>
Back to Models
- </Button>
+ </TremorButton>
<Title>Public Model Name: {getDisplayModelName(modelData)}</Title>
- <Text className="text-gray-500 font-mono">{modelData.model_info.id}</Text>
+ <Text className="text-gray-500 font-mono">
+ {modelData.model_info.id}
+ </Text>
</div>
<div className="flex gap-2">
{isAdmin && (
@@ -277,7 +308,12 @@ export default function ModelInfoView({
<TabPanels>
<TabPanel>
{/* Overview Grid */}
- <Grid numItems={1} numItemsSm={2} numItemsLg={3} className="gap-6 mb-6">
+ <Grid
+ numItems={1}
+ numItemsSm={2}
+ numItemsLg={3}
+ className="gap-6 mb-6"
+ >
<Card>
<Text>Provider</Text>
<div className="mt-2 flex items-center space-x-2">
@@ -291,9 +327,11 @@ export default function ModelInfoView({
const target = e.target as HTMLImageElement;
const parent = target.parentElement;
if (parent) {
- const fallbackDiv = document.createElement('div');
- fallbackDiv.className = 'w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs';
- fallbackDiv.textContent = modelData.provider?.charAt(0) || '-';
+ const fallbackDiv = document.createElement("div");
+ fallbackDiv.className =
+ "w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs";
+ fallbackDiv.textContent =
+ modelData.provider?.charAt(0) || "-";
parent.replaceChild(fallbackDiv, target);
}
}}
@@ -320,20 +358,43 @@ export default function ModelInfoView({
{/* Audit info shown as a subtle banner below the overview */}
<div className="mb-6 text-sm text-gray-500 flex items-center gap-x-6">
<div className="flex items-center gap-x-2">
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
+ <svg
+ className="w-4 h-4"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="2"
+ d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
+ />
</svg>
- Created At {modelData.model_info.created_at
- ? new Date(modelData.model_info.created_at).toLocaleDateString('en-US', {
- month: 'short',
- day: 'numeric',
- year: 'numeric'
+ Created At{" "}
+ {modelData.model_info.created_at
+ ? new Date(
+ modelData.model_info.created_at
+ ).toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
})
: "Not Set"}
</div>
<div className="flex items-center gap-x-2">
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
+ <svg
+ className="w-4 h-4"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="2"
+ d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
+ />
</svg>
Created By {modelData.model_info.created_by || "Not Set"}
</div>
@@ -358,303 +419,397 @@ export default function ModelInfoView({
form={form}
onFinish={handleModelUpdate}
initialValues={{
- model_name: localModelData.model_name,
- litellm_model_name: localModelData.litellm_model_name,
- api_base: localModelData.litellm_params.api_base,
- custom_llm_provider: localModelData.litellm_params.custom_llm_provider,
- organization: localModelData.litellm_params.organization,
- tpm: localModelData.litellm_params.tpm,
- rpm: localModelData.litellm_params.rpm,
- max_retries: localModelData.litellm_params.max_retries,
- timeout: localModelData.litellm_params.timeout,
- stream_timeout: localModelData.litellm_params.stream_timeout,
- input_cost: localModelData.litellm_params.input_cost_per_token ?
- (localModelData.litellm_params.input_cost_per_token * 1_000_000) : localModelData.model_info?.input_cost_per_token * 1_000_000 || null,
- output_cost: localModelData.litellm_params?.output_cost_per_token ?
- (localModelData.litellm_params.output_cost_per_token * 1_000_000) : localModelData.model_info?.output_cost_per_token * 1_000_000 || null,
- cache_control: localModelData.litellm_params?.cache_control_injection_points ? true : false,
- cache_control_injection_points: localModelData.litellm_params?.cache_control_injection_points || [],
- model_access_group: Array.isArray(localModelData.model_info?.access_groups) ? localModelData.model_info.access_groups : [],
- }}
- layout="vertical"
- onValuesChange={() => setIsDirty(true)}
- >
- <div className="space-y-4">
+ model_name: localModelData.model_name,
+ litellm_model_name: localModelData.litellm_model_name,
+ api_base: localModelData.litellm_params.api_base,
+ custom_llm_provider:
+ localModelData.litellm_params.custom_llm_provider,
+ organization: localModelData.litellm_params.organization,
+ tpm: localModelData.litellm_params.tpm,
+ rpm: localModelData.litellm_params.rpm,
+ max_retries: localModelData.litellm_params.max_retries,
+ timeout: localModelData.litellm_params.timeout,
+ stream_timeout:
+ localModelData.litellm_params.stream_timeout,
+ input_cost: localModelData.litellm_params
+ .input_cost_per_token
+ ? localModelData.litellm_params.input_cost_per_token *
+ 1_000_000
+ : localModelData.model_info?.input_cost_per_token *
+ 1_000_000 || null,
+ output_cost: localModelData.litellm_params
+ ?.output_cost_per_token
+ ? localModelData.litellm_params.output_cost_per_token *
+ 1_000_000
+ : localModelData.model_info?.output_cost_per_token *
+ 1_000_000 || null,
+ cache_control: localModelData.litellm_params
+ ?.cache_control_injection_points
+ ? true
+ : false,
+ cache_control_injection_points:
+ localModelData.litellm_params
+ ?.cache_control_injection_points || [],
+ model_access_group: Array.isArray(
+ localModelData.model_info?.access_groups
+ )
+ ? localModelData.model_info.access_groups
+ : [],
+ }}
+ layout="vertical"
+ onValuesChange={() => setIsDirty(true)}
+ >
<div className="space-y-4">
- <div>
- <Text className="font-medium">Model Name</Text>
- {isEditing ? (
- <Form.Item name="model_name" className="mb-0">
- <TextInput placeholder="Enter model name" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">{localModelData.model_name}</div>
- )}
- </div>
+ <div className="space-y-4">
+ <div>
+ <Text className="font-medium">Model Name</Text>
+ {isEditing ? (
+ <Form.Item name="model_name" className="mb-0">
+ <TextInput placeholder="Enter model name" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.model_name}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">LiteLLM Model Name</Text>
- {isEditing ? (
- <Form.Item name="litellm_model_name" className="mb-0">
- <TextInput placeholder="Enter LiteLLM model name" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">{localModelData.litellm_model_name}</div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">LiteLLM Model Name</Text>
+ {isEditing ? (
+ <Form.Item name="litellm_model_name" className="mb-0">
+ <TextInput placeholder="Enter LiteLLM model name" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_model_name}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">Input Cost (per 1M tokens)</Text>
- {isEditing ? (
- <Form.Item name="input_cost" className="mb-0">
- <NumericalInput placeholder="Enter input cost" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData?.litellm_params?.input_cost_per_token
- ? (localModelData.litellm_params?.input_cost_per_token * 1_000_000).toFixed(4)
- : localModelData?.model_info?.input_cost_per_token ? (localModelData.model_info.input_cost_per_token * 1_000_000).toFixed(4) : null}
- </div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">
+ Input Cost (per 1M tokens)
+ </Text>
+ {isEditing ? (
+ <Form.Item name="input_cost" className="mb-0">
+ <NumericalInput placeholder="Enter input cost" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData?.litellm_params
+ ?.input_cost_per_token
+ ? (
+ localModelData.litellm_params
+ ?.input_cost_per_token * 1_000_000
+ ).toFixed(4)
+ : localModelData?.model_info?.input_cost_per_token
+ ? (
+ localModelData.model_info
+ .input_cost_per_token * 1_000_000
+ ).toFixed(4)
+ : null}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">Output Cost (per 1M tokens)</Text>
- {isEditing ? (
- <Form.Item name="output_cost" className="mb-0">
- <NumericalInput placeholder="Enter output cost" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData?.litellm_params?.output_cost_per_token
- ? (localModelData.litellm_params.output_cost_per_token * 1_000_000).toFixed(4)
- : localModelData?.model_info?.output_cost_per_token ? (localModelData.model_info.output_cost_per_token * 1_000_000).toFixed(4) : null}
- </div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">
+ Output Cost (per 1M tokens)
+ </Text>
+ {isEditing ? (
+ <Form.Item name="output_cost" className="mb-0">
+ <NumericalInput placeholder="Enter output cost" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData?.litellm_params
+ ?.output_cost_per_token
+ ? (
+ localModelData.litellm_params
+ .output_cost_per_token * 1_000_000
+ ).toFixed(4)
+ : localModelData?.model_info
+ ?.output_cost_per_token
+ ? (
+ localModelData.model_info
+ .output_cost_per_token * 1_000_000
+ ).toFixed(4)
+ : null}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">API Base</Text>
- {isEditing ? (
- <Form.Item name="api_base" className="mb-0">
- <TextInput placeholder="Enter API base" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData.litellm_params?.api_base || "Not Set"}
- </div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">API Base</Text>
+ {isEditing ? (
+ <Form.Item name="api_base" className="mb-0">
+ <TextInput placeholder="Enter API base" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_params?.api_base ||
+ "Not Set"}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">Custom LLM Provider</Text>
- {isEditing ? (
- <Form.Item name="custom_llm_provider" className="mb-0">
- <TextInput placeholder="Enter custom LLM provider" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData.litellm_params?.custom_llm_provider || "Not Set"}
- </div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">Custom LLM Provider</Text>
+ {isEditing ? (
+ <Form.Item
+ name="custom_llm_provider"
+ className="mb-0"
+ >
+ <TextInput placeholder="Enter custom LLM provider" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_params
+ ?.custom_llm_provider || "Not Set"}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">Organization</Text>
- {isEditing ? (
- <Form.Item name="organization" className="mb-0">
- <TextInput placeholder="Enter organization" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData.litellm_params?.organization || "Not Set"}
- </div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">Organization</Text>
+ {isEditing ? (
+ <Form.Item name="organization" className="mb-0">
+ <TextInput placeholder="Enter organization" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_params?.organization ||
+ "Not Set"}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">TPM (Tokens per Minute)</Text>
- {isEditing ? (
- <Form.Item name="tpm" className="mb-0">
- <NumericalInput placeholder="Enter TPM" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData.litellm_params?.tpm || "Not Set"}
- </div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">
+ TPM (Tokens per Minute)
+ </Text>
+ {isEditing ? (
+ <Form.Item name="tpm" className="mb-0">
+ <NumericalInput placeholder="Enter TPM" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_params?.tpm || "Not Set"}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">RPM (Requests per Minute)</Text>
- {isEditing ? (
- <Form.Item name="rpm" className="mb-0">
- <NumericalInput placeholder="Enter RPM" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData.litellm_params?.rpm || "Not Set"}
- </div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">
+ RPM (Requests per Minute)
+ </Text>
+ {isEditing ? (
+ <Form.Item name="rpm" className="mb-0">
+ <NumericalInput placeholder="Enter RPM" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_params?.rpm || "Not Set"}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">Max Retries</Text>
- {isEditing ? (
- <Form.Item name="max_retries" className="mb-0">
- <NumericalInput placeholder="Enter max retries" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData.litellm_params?.max_retries || "Not Set"}
- </div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">Max Retries</Text>
+ {isEditing ? (
+ <Form.Item name="max_retries" className="mb-0">
+ <NumericalInput placeholder="Enter max retries" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_params?.max_retries ||
+ "Not Set"}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">Timeout (seconds)</Text>
- {isEditing ? (
- <Form.Item name="timeout" className="mb-0">
- <NumericalInput placeholder="Enter timeout" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData.litellm_params?.timeout || "Not Set"}
- </div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">Timeout (seconds)</Text>
+ {isEditing ? (
+ <Form.Item name="timeout" className="mb-0">
+ <NumericalInput placeholder="Enter timeout" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_params?.timeout ||
+ "Not Set"}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">Stream Timeout (seconds)</Text>
- {isEditing ? (
- <Form.Item name="stream_timeout" className="mb-0">
- <NumericalInput placeholder="Enter stream timeout" />
- </Form.Item>
- ) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData.litellm_params?.stream_timeout || "Not Set"}
- </div>
- )}
- </div>
+ <div>
+ <Text className="font-medium">
+ Stream Timeout (seconds)
+ </Text>
+ {isEditing ? (
+ <Form.Item name="stream_timeout" className="mb-0">
+ <NumericalInput placeholder="Enter stream timeout" />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_params?.stream_timeout ||
+ "Not Set"}
+ </div>
+ )}
+ </div>
+
+ <div>
+ <Text className="font-medium">Model Access Groups</Text>
+ {isEditing ? (
+ <Form.Item name="model_access_group" className="mb-0">
+ <Select
+ mode="tags"
+ showSearch
+ placeholder="Select existing groups or type to create new ones"
+ optionFilterProp="children"
+ tokenSeparators={[","]}
+ maxTagCount="responsive"
+ allowClear
+ style={{ width: "100%" }}
+ options={modelAccessGroups?.map((group) => ({
+ value: group,
+ label: group,
+ }))}
+ />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.model_info?.access_groups ? (
+ Array.isArray(
+ localModelData.model_info.access_groups
+ ) ? (
+ localModelData.model_info.access_groups.length >
+ 0 ? (
+ <div className="flex flex-wrap gap-1">
+ {localModelData.model_info.access_groups.map(
+ (group: string, index: number) => (
+ <span
+ key={index}
+ className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
+ >
+ {group}
+ </span>
+ )
+ )}
+ </div>
+ ) : (
+ "No groups assigned"
+ )
+ ) : (
+ localModelData.model_info.access_groups
+ )
+ ) : (
+ "Not Set"
+ )}
+ </div>
+ )}
+ </div>
- <div>
- <Text className="font-medium">Model Access Groups</Text>
+ {/* Cache Control Section */}
{isEditing ? (
- <Form.Item name="model_access_group" className="mb-0">
- <Select
- mode="tags"
- showSearch
- placeholder="Select existing groups or type to create new ones"
- optionFilterProp="children"
- tokenSeparators={[',']}
- maxTagCount="responsive"
- allowClear
- style={{ width: '100%' }}
- options={modelAccessGroups?.map((group) => ({
- value: group,
- label: group
- }))}
- />
- </Form.Item>
+ <CacheControlSettings
+ form={form}
+ showCacheControl={showCacheControl}
+ onCacheControlChange={(checked) =>
+ setShowCacheControl(checked)
+ }
+ />
) : (
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData.model_info?.access_groups ? (
- Array.isArray(localModelData.model_info.access_groups) ? (
- localModelData.model_info.access_groups.length > 0 ? (
- <div className="flex flex-wrap gap-1">
- {localModelData.model_info.access_groups.map((group: string, index: number) => (
- <span key={index} className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
- {group}
- </span>
- ))}
+ <div>
+ <Text className="font-medium">Cache Control</Text>
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ {localModelData.litellm_params
+ ?.cache_control_injection_points ? (
+ <div>
+ <p>Enabled</p>
+ <div className="mt-2">
+ {localModelData.litellm_params.cache_control_injection_points.map(
+ (point: any, i: number) => (
+ <div
+ key={i}
+ className="text-sm text-gray-600 mb-1"
+ >
+ Location: {point.location},
+ {point.role && (
+ <span> Role: {point.role}</span>
+ )}
+ {point.index !== undefined && (
+ <span> Index: {point.index}</span>
+ )}
+ </div>
+ )
+ )}
</div>
- ) : "No groups assigned"
- ) : localModelData.model_info.access_groups
- ) : "Not Set"}
+ </div>
+ ) : (
+ "Disabled"
+ )}
+ </div>
</div>
)}
- </div>
-
- {/* Cache Control Section */}
- {isEditing ? (
- <CacheControlSettings
- form={form}
- showCacheControl={showCacheControl}
- onCacheControlChange={(checked) => setShowCacheControl(checked)}
- />
- ) : (
<div>
- <Text className="font-medium">Cache Control</Text>
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {localModelData.litellm_params?.cache_control_injection_points ? (
- <div>
- <p>Enabled</p>
- <div className="mt-2">
- {localModelData.litellm_params.cache_control_injection_points.map((point: any, i: number) => (
- <div key={i} className="text-sm text-gray-600 mb-1">
- Location: {point.location},
- {point.role && <span> Role: {point.role}</span>}
- {point.index !== undefined && <span> Index: {point.index}</span>}
- </div>
- ))}
- </div>
- </div>
- ) : (
- "Disabled"
- )}
- </div>
+ <Text className="font-medium">Model Info</Text>
+ {isEditing ? (
+ <Form.Item name="model_info" className="mb-0">
+ <Input.TextArea
+ rows={4}
+ placeholder='{"gpt-4": 100, "claude-v1": 200}'
+ defaultValue={JSON.stringify(
+ modelData.model_info,
+ null,
+ 2
+ )}
+ />
+ </Form.Item>
+ ) : (
+ <div className="mt-1 p-2 bg-gray-50 rounded">
+ <pre className="bg-gray-100 p-2 rounded text-xs overflow-auto mt-1">
+ {JSON.stringify(
+ localModelData.model_info,
+ null,
+ 2
+ )}
+ </pre>
+ </div>
+ )}
</div>
- )}
-
- <div>
- <Text className="font-medium">Model Info</Text>
- {isEditing ? (
- <Form.Item name="model_info" className="mb-0">
- <Input.TextArea
- rows={4}
- placeholder='{"gpt-4": 100, "claude-v1": 200}'
- defaultValue={JSON.stringify(modelData.model_info, null, 2)}
- />
- </Form.Item>
- ) : (
+ <div>
+ <Text className="font-medium">Team ID</Text>
<div className="mt-1 p-2 bg-gray-50 rounded">
- <pre className="bg-gray-100 p-2 rounded text-xs overflow-auto mt-1">
- {JSON.stringify(localModelData.model_info, null, 2)}
- </pre>
+ {modelData.model_info.team_id || "Not Set"}
</div>
- )}
- </div>
- <div>
- <Text className="font-medium">Team ID</Text>
- <div className="mt-1 p-2 bg-gray-50 rounded">
- {modelData.model_info.team_id || "Not Set"}
</div>
</div>
- </div>
- {isEditing && (
- <div className="mt-6 flex justify-end gap-2">
- <TremorButton
- variant="secondary"
- onClick={() => {
- form.resetFields();
- setIsDirty(false);
- setIsEditing(false);
- }}
- >
- Cancel
- </TremorButton>
- <TremorButton
- variant="primary"
- onClick={() => form.submit()}
- loading={isSaving}
- >
- Save Changes
- </TremorButton>
- </div>
- )}
- </div>
+ {isEditing && (
+ <div className="mt-6 flex justify-end gap-2">
+ <TremorButton
+ variant="secondary"
+ onClick={() => {
+ form.resetFields();
+ setIsDirty(false);
+ setIsEditing(false);
+ }}
+ >
+ Cancel
+ </TremorButton>
+ <TremorButton
+ variant="primary"
+ onClick={() => form.submit()}
+ loading={isSaving}
+ >
+ Save Changes
+ </TremorButton>
+ </div>
+ )}
+ </div>
</Form>
) : (
<Text>Loading...</Text>
@@ -676,11 +831,19 @@ export default function ModelInfoView({
{isDeleteModalOpen && (
<div className="fixed z-10 inset-0 overflow-y-auto">
<div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
- <div className="fixed inset-0 transition-opacity" aria-hidden="true">
+ <div
+ className="fixed inset-0 transition-opacity"
+ aria-hidden="true"
+ >
<div className="absolute inset-0 bg-gray-500 opacity-75"></div>
</div>
- <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
+ <span
+ className="hidden sm:inline-block sm:align-middle sm:h-screen"
+ aria-hidden="true"
+ >
+ &#8203;
+ </span>
<div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
<div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
@@ -698,11 +861,7 @@ export default function ModelInfoView({
</div>
</div>
<div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
- <Button
- onClick={handleDelete}
- className="ml-2"
- danger
- >
+ <Button onClick={handleDelete} className="ml-2" danger>
Delete
</Button>
<Button onClick={() => setIsDeleteModalOpen(false)}>
@@ -714,8 +873,7 @@ export default function ModelInfoView({
</div>
)}
- {isCredentialModalOpen &&
- !usingExistingCredential ? (
+ {isCredentialModalOpen && !usingExistingCredential ? (
<ReuseCredentialsModal
isVisible={isCredentialModalOpen}
onCancel={() => setIsCredentialModalOpen(false)}
@@ -723,7 +881,7 @@ export default function ModelInfoView({
existingCredential={existingCredential}
setIsCredentialModalOpen={setIsCredentialModalOpen}
/>
- ): (
+ ) : (
<Modal
open={isCredentialModalOpen}
onCancel={() => setIsCredentialModalOpen(false)}
@@ -734,4 +892,4 @@ export default function ModelInfoView({
)}
</div>
);
-}
\ No newline at end of file
+}
diff --git a/ui/litellm-dashboard/src/components/organization/organization_view.tsx b/ui/litellm-dashboard/src/components/organization/organization_view.tsx
index 5efbd2ba91e..d9ce9005ae2 100644
--- a/ui/litellm-dashboard/src/components/organization/organization_view.tsx
+++ b/ui/litellm-dashboard/src/components/organization/organization_view.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from "react";
+import React, { useState, useEffect } from "react"
import {
Card,
Title,
@@ -18,29 +18,37 @@ import {
TableBody,
TableCell,
Button as TremorButton,
- Icon
-} from "@tremor/react";
-import NumericalInput from "../shared/numerical_input";
-import { Button, Form, Input, Select, message, Tooltip } from "antd";
-import { InfoCircleOutlined } from '@ant-design/icons';
-import { PencilAltIcon, TrashIcon } from "@heroicons/react/outline";
-import { getModelDisplayName } from "../key_team_helpers/fetch_available_models_team_key";
-import { Member, Organization, organizationInfoCall, organizationMemberAddCall, organizationMemberUpdateCall, organizationMemberDeleteCall, organizationUpdateCall } from "../networking";
-import UserSearchModal from "../common_components/user_search_modal";
-import MemberModal from "../team/edit_membership";
-import ObjectPermissionsView from "../object_permissions_view";
-import VectorStoreSelector from "../vector_store_management/VectorStoreSelector";
-import MCPServerSelector from "../mcp_server_management/MCPServerSelector";
-import { formatNumberWithCommas } from "@/utils/dataUtils";
+ Icon,
+} from "@tremor/react"
+import NumericalInput from "../shared/numerical_input"
+import { Button, Form, Input, Select, message, Tooltip } from "antd"
+import { InfoCircleOutlined } from "@ant-design/icons"
+import { ArrowLeftIcon, PencilAltIcon, TrashIcon } from "@heroicons/react/outline"
+import { getModelDisplayName } from "../key_team_helpers/fetch_available_models_team_key"
+import {
+ Member,
+ Organization,
+ organizationInfoCall,
+ organizationMemberAddCall,
+ organizationMemberUpdateCall,
+ organizationMemberDeleteCall,
+ organizationUpdateCall,
+} from "../networking"
+import UserSearchModal from "../common_components/user_search_modal"
+import MemberModal from "../team/edit_membership"
+import ObjectPermissionsView from "../object_permissions_view"
+import VectorStoreSelector from "../vector_store_management/VectorStoreSelector"
+import MCPServerSelector from "../mcp_server_management/MCPServerSelector"
+import { formatNumberWithCommas } from "@/utils/dataUtils"
interface OrganizationInfoProps {
- organizationId: string;
- onClose: () => void;
- accessToken: string | null;
- is_org_admin: boolean;
- is_proxy_admin: boolean;
- userModels: string[];
- editOrg: boolean;
+ organizationId: string
+ onClose: () => void
+ accessToken: string | null
+ is_org_admin: boolean
+ is_proxy_admin: boolean
+ userModels: string[]
+ editOrg: boolean
}
const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
@@ -50,40 +58,40 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
is_org_admin,
is_proxy_admin,
userModels,
- editOrg
+ editOrg,
}) => {
- const [orgData, setOrgData] = useState<Organization | null>(null);
- const [loading, setLoading] = useState(true);
- const [form] = Form.useForm();
- const [isEditing, setIsEditing] = useState(false);
- const [isAddMemberModalVisible, setIsAddMemberModalVisible] = useState(false);
- const [isEditMemberModalVisible, setIsEditMemberModalVisible] = useState(false);
- const [selectedEditMember, setSelectedEditMember] = useState<Member | null>(null);
+ const [orgData, setOrgData] = useState<Organization | null>(null)
+ const [loading, setLoading] = useState(true)
+ const [form] = Form.useForm()
+ const [isEditing, setIsEditing] = useState(false)
+ const [isAddMemberModalVisible, setIsAddMemberModalVisible] = useState(false)
+ const [isEditMemberModalVisible, setIsEditMemberModalVisible] = useState(false)
+ const [selectedEditMember, setSelectedEditMember] = useState<Member | null>(null)
- const canEditOrg = is_org_admin || is_proxy_admin;
+ const canEditOrg = is_org_admin || is_proxy_admin
const fetchOrgInfo = async () => {
try {
- setLoading(true);
- if (!accessToken) return;
- const response = await organizationInfoCall(accessToken, organizationId);
- setOrgData(response);
+ setLoading(true)
+ if (!accessToken) return
+ const response = await organizationInfoCall(accessToken, organizationId)
+ setOrgData(response)
} catch (error) {
- message.error("Failed to load organization information");
- console.error("Error fetching organization info:", error);
+ message.error("Failed to load organization information")
+ console.error("Error fetching organization info:", error)
} finally {
- setLoading(false);
+ setLoading(false)
}
- };
+ }
useEffect(() => {
- fetchOrgInfo();
- }, [organizationId, accessToken]);
+ fetchOrgInfo()
+ }, [organizationId, accessToken])
const handleMemberAdd = async (values: any) => {
try {
if (accessToken == null) {
- return;
+ return
}
const member: Member = {
@@ -91,21 +99,21 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
user_id: values.user_id,
role: values.role,
}
- const response = await organizationMemberAddCall(accessToken, organizationId, member);
+ const response = await organizationMemberAddCall(accessToken, organizationId, member)
- message.success("Organization member added successfully");
- setIsAddMemberModalVisible(false);
- form.resetFields();
- fetchOrgInfo();
+ message.success("Organization member added successfully")
+ setIsAddMemberModalVisible(false)
+ form.resetFields()
+ fetchOrgInfo()
} catch (error) {
- message.error("Failed to add organization member");
- console.error("Error adding organization member:", error);
+ message.error("Failed to add organization member")
+ console.error("Error adding organization member:", error)
}
- };
+ }
const handleMemberUpdate = async (values: any) => {
try {
- if (!accessToken) return;
+ if (!accessToken) return
const member: Member = {
user_email: values.user_email,
@@ -113,35 +121,35 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
role: values.role,
}
- const response = await organizationMemberUpdateCall(accessToken, organizationId, member);
- message.success("Organization member updated successfully");
- setIsEditMemberModalVisible(false);
- form.resetFields();
- fetchOrgInfo();
+ const response = await organizationMemberUpdateCall(accessToken, organizationId, member)
+ message.success("Organization member updated successfully")
+ setIsEditMemberModalVisible(false)
+ form.resetFields()
+ fetchOrgInfo()
} catch (error) {
- message.error("Failed to update organization member");
- console.error("Error updating organization member:", error);
+ message.error("Failed to update organization member")
+ console.error("Error updating organization member:", error)
}
- };
+ }
const handleMemberDelete = async (values: any) => {
try {
- if (!accessToken) return;
+ if (!accessToken) return
- await organizationMemberDeleteCall(accessToken, organizationId, values.user_id);
- message.success("Organization member deleted successfully");
- setIsEditMemberModalVisible(false);
- form.resetFields();
- fetchOrgInfo();
+ await organizationMemberDeleteCall(accessToken, organizationId, values.user_id)
+ message.success("Organization member deleted successfully")
+ setIsEditMemberModalVisible(false)
+ form.resetFields()
+ fetchOrgInfo()
} catch (error) {
- message.error("Failed to delete organization member");
- console.error("Error deleting organization member:", error);
+ message.error("Failed to delete organization member")
+ console.error("Error deleting organization member:", error)
}
- };
+ }
const handleOrgUpdate = async (values: any) => {
try {
- if (!accessToken) return;
+ if (!accessToken) return
const updateData: any = {
organization_id: organizationId,
@@ -154,50 +162,55 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
budget_duration: values.budget_duration,
},
metadata: values.metadata ? JSON.parse(values.metadata) : null,
- };
+ }
// Handle object_permission updates
if (values.vector_stores !== undefined || values.mcp_servers_and_groups !== undefined) {
updateData.object_permission = {
...orgData?.object_permission,
- vector_stores: values.vector_stores || []
- };
-
+ vector_stores: values.vector_stores || [],
+ }
+
if (values.mcp_servers_and_groups !== undefined) {
- const { servers, accessGroups } = values.mcp_servers_and_groups || { servers: [], accessGroups: [] };
+ const { servers, accessGroups } = values.mcp_servers_and_groups || {
+ servers: [],
+ accessGroups: [],
+ }
if (servers && servers.length > 0) {
- updateData.object_permission.mcp_servers = servers;
+ updateData.object_permission.mcp_servers = servers
}
if (accessGroups && accessGroups.length > 0) {
- updateData.object_permission.mcp_access_groups = accessGroups;
+ updateData.object_permission.mcp_access_groups = accessGroups
}
}
}
-
- const response = await organizationUpdateCall(accessToken, updateData);
- message.success("Organization settings updated successfully");
- setIsEditing(false);
- fetchOrgInfo();
+ const response = await organizationUpdateCall(accessToken, updateData)
+
+ message.success("Organization settings updated successfully")
+ setIsEditing(false)
+ fetchOrgInfo()
} catch (error) {
- message.error("Failed to update organization settings");
- console.error("Error updating organization:", error);
+ message.error("Failed to update organization settings")
+ console.error("Error updating organization:", error)
}
- };
+ }
if (loading) {
- return <div className="p-4">Loading...</div>;
+ return <div className="p-4">Loading...</div>
}
if (!orgData) {
- return <div className="p-4">Organization not found</div>;
+ return <div className="p-4">Organization not found</div>
}
return (
<div className="w-full h-screen p-4 bg-white">
<div className="flex justify-between items-center mb-6">
<div>
- <Button onClick={onClose} className="mb-4">← Back</Button>
+ <TremorButton icon={ArrowLeftIcon} onClick={onClose} variant="light" className="mb-4">
+ Back to Organizations
+ </TremorButton>
<Title>{orgData.organization_alias}</Title>
<Text className="text-gray-500 font-mono">{orgData.organization_id}</Text>
</div>
@@ -213,138 +226,145 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
<TabPanels>
{/* Overview Panel */}
<TabPanel>
- <Grid numItems={1} numItemsSm={2} numItemsLg={3} className="gap-6">
- <Card>
+ <Grid numItems={1} numItemsSm={2} numItemsLg={3} className="gap-6">
+ <Card>
<Text>Organization Details</Text>
<div className="mt-2">
- <Text>Created: {new Date(orgData.created_at).toLocaleDateString()}</Text>
- <Text>Updated: {new Date(orgData.updated_at).toLocaleDateString()}</Text>
- <Text>Created By: {orgData.created_by}</Text>
+ <Text>Created: {new Date(orgData.created_at).toLocaleDateString()}</Text>
+ <Text>Updated: {new Date(orgData.updated_at).toLocaleDateString()}</Text>
+ <Text>Created By: {orgData.created_by}</Text>
</div>
- </Card>
+ </Card>
- <Card>
+ <Card>
<Text>Budget Status</Text>
<div className="mt-2">
- <Title>${formatNumberWithCommas(orgData.spend, 4)}</Title>
- <Text>of {orgData.litellm_budget_table.max_budget === null ? "Unlimited" : `$${formatNumberWithCommas(orgData.litellm_budget_table.max_budget, 4)}`}</Text>
- {orgData.litellm_budget_table.budget_duration && (
+ <Title>${formatNumberWithCommas(orgData.spend, 4)}</Title>
+ <Text>
+ of{" "}
+ {orgData.litellm_budget_table.max_budget === null
+ ? "Unlimited"
+ : `$${formatNumberWithCommas(orgData.litellm_budget_table.max_budget, 4)}`}
+ </Text>
+ {orgData.litellm_budget_table.budget_duration && (
<Text className="text-gray-500">Reset: {orgData.litellm_budget_table.budget_duration}</Text>
- )}
+ )}
</div>
- </Card>
+ </Card>
- <Card>
+ <Card>
<Text>Rate Limits</Text>
<div className="mt-2">
- <Text>TPM: {orgData.litellm_budget_table.tpm_limit || 'Unlimited'}</Text>
- <Text>RPM: {orgData.litellm_budget_table.rpm_limit || 'Unlimited'}</Text>
- {orgData.litellm_budget_table.max_parallel_requests && (
+ <Text>TPM: {orgData.litellm_budget_table.tpm_limit || "Unlimited"}</Text>
+ <Text>RPM: {orgData.litellm_budget_table.rpm_limit || "Unlimited"}</Text>
+ {orgData.litellm_budget_table.max_parallel_requests && (
<Text>Max Parallel Requests: {orgData.litellm_budget_table.max_parallel_requests}</Text>
- )}
+ )}
</div>
- </Card>
+ </Card>
- <Card>
+ <Card>
<Text>Models</Text>
<div className="mt-2 flex flex-wrap gap-2">
- {orgData.models.length === 0 ? (
- <Badge color="red">All proxy models</Badge>
- ) : (
- orgData.models.map((model, index) => (
- <Badge key={index} color="red">
- {model}
- </Badge>
- ))
- )}
+ {orgData.models.length === 0 ? (
+ <Badge color="red">All proxy models</Badge>
+ ) : (
+ orgData.models.map((model, index) => (
+ <Badge key={index} color="red">
+ {model}
+ </Badge>
+ ))
+ )}
</div>
- </Card>
- <Card>
+ </Card>
+ <Card>
<Text>Teams</Text>
<div className="mt-2 flex flex-wrap gap-2">
- {orgData.teams?.map((team, index) => (
+ {orgData.teams?.map((team, index) => (
<Badge key={index} color="red">
- {team.team_id}
+ {team.team_id}
</Badge>
- ))}
+ ))}
</div>
- </Card>
+ </Card>
- <ObjectPermissionsView
- objectPermission={orgData.object_permission}
- variant="card"
- accessToken={accessToken}
- />
+ <ObjectPermissionsView
+ objectPermission={orgData.object_permission}
+ variant="card"
+ accessToken={accessToken}
+ />
</Grid>
</TabPanel>
{/* Budget Panel */}
<TabPanel>
<div className="space-y-4">
- <Card className="w-full mx-auto flex-auto overflow-y-auto max-h-[75vh]">
+ <Card className="w-full mx-auto flex-auto overflow-y-auto max-h-[75vh]">
<Table>
- <TableHead>
+ <TableHead>
<TableRow>
- <TableHeaderCell>User ID</TableHeaderCell>
- <TableHeaderCell>Role</TableHeaderCell>
- <TableHeaderCell>Spend</TableHeaderCell>
- <TableHeaderCell>Created At</TableHeaderCell>
- <TableHeaderCell></TableHeaderCell>
+ <TableHeaderCell>User ID</TableHeaderCell>
+ <TableHeaderCell>Role</TableHeaderCell>
+ <TableHeaderCell>Spend</TableHeaderCell>
+ <TableHeaderCell>Created At</TableHeaderCell>
+ <TableHeaderCell></TableHeaderCell>
</TableRow>
- </TableHead>
+ </TableHead>
- <TableBody>
+ <TableBody>
{orgData.members?.map((member, index) => (
- <TableRow key={index}>
+ <TableRow key={index}>
<TableCell>
- <Text className="font-mono">{member.user_id}</Text>
+ <Text className="font-mono">{member.user_id}</Text>
</TableCell>
<TableCell>
- <Text className="font-mono">{member.user_role}</Text>
+ <Text className="font-mono">{member.user_role}</Text>
</TableCell>
<TableCell>
- <Text>${formatNumberWithCommas(member.spend, 4)}</Text>
+ <Text>${formatNumberWithCommas(member.spend, 4)}</Text>
</TableCell>
<TableCell>
- <Text>{new Date(member.created_at).toLocaleString()}</Text>
+ <Text>{new Date(member.created_at).toLocaleString()}</Text>
</TableCell>
<TableCell>
- {canEditOrg && (
+ {canEditOrg && (
<>
- <Icon
+ <Icon
icon={PencilAltIcon}
size="sm"
onClick={() => {
- setSelectedEditMember({
- "role": member.user_role,
- "user_email": member.user_email,
- "user_id": member.user_id
- });
- setIsEditMemberModalVisible(true);
+ setSelectedEditMember({
+ role: member.user_role,
+ user_email: member.user_email,
+ user_id: member.user_id,
+ })
+ setIsEditMemberModalVisible(true)
}}
- />
- <Icon
+ />
+ <Icon
icon={TrashIcon}
size="sm"
onClick={() => {
- handleMemberDelete(member);
+ handleMemberDelete(member)
}}
- />
+ />
</>
- )}
+ )}
</TableCell>
- </TableRow>
+ </TableRow>
))}
- </TableBody>
+ </TableBody>
</Table>
- </Card>
- {canEditOrg && (
- <TremorButton onClick={() => {
- setIsAddMemberModalVisible(true);
- }}>
- Add Member
+ </Card>
+ {canEditOrg && (
+ <TremorButton
+ onClick={() => {
+ setIsAddMemberModalVisible(true)
+ }}
+ >
+ Add Member
</TremorButton>
- )}
+ )}
</div>
</TabPanel>
@@ -353,12 +373,8 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
<Card className="overflow-y-auto max-h-[65vh]">
<div className="flex justify-between items-center mb-4">
<Title>Organization Settings</Title>
- {(canEditOrg && !isEditing) && (
- <TremorButton
- onClick={() => setIsEditing(true)}
- >
- Edit Settings
- </TremorButton>
+ {canEditOrg && !isEditing && (
+ <TremorButton onClick={() => setIsEditing(true)}>Edit Settings</TremorButton>
)}
</div>
@@ -377,24 +393,26 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
vector_stores: orgData.object_permission?.vector_stores || [],
mcp_servers_and_groups: {
servers: orgData.object_permission?.mcp_servers || [],
- accessGroups: orgData.object_permission?.mcp_access_groups || []
- }
+ accessGroups: orgData.object_permission?.mcp_access_groups || [],
+ },
}}
layout="vertical"
>
<Form.Item
label="Organization Name"
name="organization_alias"
- rules={[{ required: true, message: "Please input an organization name" }]}
+ rules={[
+ {
+ required: true,
+ message: "Please input an organization name",
+ },
+ ]}
>
<TextInput />
</Form.Item>
-
+
<Form.Item label="Models" name="models">
- <Select
- mode="multiple"
- placeholder="Select models"
- >
+ <Select mode="multiple" placeholder="Select models">
<Select.Option key="all-proxy-models" value="all-proxy-models">
All Proxy Models
</Select.Option>
@@ -428,8 +446,8 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
<Form.Item label="Vector Stores" name="vector_stores">
<VectorStoreSelector
- onChange={(values) => form.setFieldValue('vector_stores', values)}
- value={form.getFieldValue('vector_stores')}
+ onChange={(values) => form.setFieldValue("vector_stores", values)}
+ value={form.getFieldValue("vector_stores")}
accessToken={accessToken || ""}
placeholder="Select vector stores"
/>
@@ -437,25 +455,21 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
<Form.Item label="MCP Servers & Access Groups" name="mcp_servers_and_groups">
<MCPServerSelector
- onChange={(values) => form.setFieldValue('mcp_servers_and_groups', values)}
- value={form.getFieldValue('mcp_servers_and_groups')}
+ onChange={(values) => form.setFieldValue("mcp_servers_and_groups", values)}
+ value={form.getFieldValue("mcp_servers_and_groups")}
accessToken={accessToken || ""}
placeholder="Select MCP servers and access groups"
/>
</Form.Item>
- <Form.Item label="Metadata" name="metadata">
+ <Form.Item label="Metadata" name="metadata">
<Input.TextArea rows={4} />
</Form.Item>
<div className="sticky z-10 bg-white p-4 border-t border-gray-200 bottom-[-1.5rem] inset-x-[-1.5rem]">
<div className="flex justify-end items-center gap-2">
- <Button onClick={() => setIsEditing(false)}>
- Cancel
- </Button>
- <TremorButton type="submit">
- Save Changes
- </TremorButton>
+ <Button onClick={() => setIsEditing(false)}>Cancel</Button>
+ <TremorButton type="submit">Save Changes</TremorButton>
</div>
</div>
</Form>
@@ -485,17 +499,22 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
</div>
<div>
<Text className="font-medium">Rate Limits</Text>
- <div>TPM: {orgData.litellm_budget_table.tpm_limit || 'Unlimited'}</div>
- <div>RPM: {orgData.litellm_budget_table.rpm_limit || 'Unlimited'}</div>
+ <div>TPM: {orgData.litellm_budget_table.tpm_limit || "Unlimited"}</div>
+ <div>RPM: {orgData.litellm_budget_table.rpm_limit || "Unlimited"}</div>
</div>
<div>
<Text className="font-medium">Budget</Text>
- <div>Max: {orgData.litellm_budget_table.max_budget !== null ? `$${formatNumberWithCommas(orgData.litellm_budget_table.max_budget, 4)}` : 'No Limit'}</div>
- <div>Reset: {orgData.litellm_budget_table.budget_duration || 'Never'}</div>
+ <div>
+ Max:{" "}
+ {orgData.litellm_budget_table.max_budget !== null
+ ? `$${formatNumberWithCommas(orgData.litellm_budget_table.max_budget, 4)}`
+ : "No Limit"}
+ </div>
+ <div>Reset: {orgData.litellm_budget_table.budget_duration || "Never"}</div>
</div>
- <ObjectPermissionsView
- objectPermission={orgData.object_permission}
+ <ObjectPermissionsView
+ objectPermission={orgData.object_permission}
variant="inline"
className="pt-4 border-t border-gray-200"
accessToken={accessToken}
@@ -513,9 +532,21 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
accessToken={accessToken}
title="Add Organization Member"
roles={[
- { label: "org_admin", value: "org_admin", description: "Can add and remove members, and change their roles." },
- { label: "internal_user", value: "internal_user", description: "Can view/create keys for themselves within organization." },
- { label: "internal_user_viewer", value: "internal_user_viewer", description: "Can only view their keys within organization." }
+ {
+ label: "org_admin",
+ value: "org_admin",
+ description: "Can add and remove members, and change their roles.",
+ },
+ {
+ label: "internal_user",
+ value: "internal_user",
+ description: "Can view/create keys for themselves within organization.",
+ },
+ {
+ label: "internal_user_viewer",
+ value: "internal_user_viewer",
+ description: "Can only view their keys within organization.",
+ },
]}
defaultRole="internal_user"
/>
@@ -532,12 +563,12 @@ const OrganizationInfoView: React.FC<OrganizationInfoProps> = ({
roleOptions: [
{ label: "Org Admin", value: "org_admin" },
{ label: "Internal User", value: "internal_user" },
- { label: "Internal User Viewer", value: "internal_user_viewer" }
- ]
+ { label: "Internal User Viewer", value: "internal_user_viewer" },
+ ],
}}
/>
</div>
- );
-};
+ )
+}
-export default OrganizationInfoView;
\ No newline at end of file
+export default OrganizationInfoView
diff --git a/ui/litellm-dashboard/src/components/organizations.tsx b/ui/litellm-dashboard/src/components/organizations.tsx
index a0bacf12059..cb727d4dd64 100644
--- a/ui/litellm-dashboard/src/components/organizations.tsx
+++ b/ui/litellm-dashboard/src/components/organizations.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect } from "react"
import {
Table,
TableHead,
@@ -18,38 +18,41 @@ import {
Tab,
TabPanels,
TabPanel,
-} from "@tremor/react";
-import NumericalInput from "./shared/numerical_input";
-import { Input } from "antd";
-import { Modal, Form, Tooltip, Select as Select2 } from "antd";
-import { InfoCircleOutlined } from '@ant-design/icons';
-import { PencilAltIcon, TrashIcon, RefreshIcon, ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/outline";
-import { TextInput } from "@tremor/react";
-import { getModelDisplayName } from './key_team_helpers/fetch_available_models_team_key';
-import { message } from 'antd';
-import OrganizationInfoView from './organization/organization_view';
-import { Organization, organizationListCall, organizationCreateCall, organizationDeleteCall } from './networking';
-import VectorStoreSelector from "./vector_store_management/VectorStoreSelector";
-import MCPServerSelector from "./mcp_server_management/MCPServerSelector";
-import { formatNumberWithCommas } from "../utils/dataUtils";
+} from "@tremor/react"
+import NumericalInput from "./shared/numerical_input"
+import { Input } from "antd"
+import { Modal, Form, Tooltip, Select as Select2 } from "antd"
+import { InfoCircleOutlined } from "@ant-design/icons"
+import { PencilAltIcon, TrashIcon, RefreshIcon, ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/outline"
+import { TextInput } from "@tremor/react"
+import { getModelDisplayName } from "./key_team_helpers/fetch_available_models_team_key"
+import { message } from "antd"
+import OrganizationInfoView from "./organization/organization_view"
+import { Organization, organizationListCall, organizationCreateCall, organizationDeleteCall } from "./networking"
+import VectorStoreSelector from "./vector_store_management/VectorStoreSelector"
+import MCPServerSelector from "./mcp_server_management/MCPServerSelector"
+import { formatNumberWithCommas } from "../utils/dataUtils"
interface OrganizationsTableProps {
- organizations: Organization[];
- userRole: string;
- userModels: string[];
- accessToken: string | null;
- lastRefreshed?: string;
- handleRefreshClick?: () => void;
- currentOrg?: any;
- guardrailsList?: string[];
- setOrganizations: (organizations: Organization[]) => void;
- premiumUser: boolean;
+ organizations: Organization[]
+ userRole: string
+ userModels: string[]
+ accessToken: string | null
+ lastRefreshed?: string
+ handleRefreshClick?: () => void
+ currentOrg?: any
+ guardrailsList?: string[]
+ setOrganizations: (organizations: Organization[]) => void
+ premiumUser: boolean
}
-export const fetchOrganizations = async (accessToken: string, setOrganizations: (organizations: Organization[]) => void) => {
- const organizations = await organizationListCall(accessToken);
- setOrganizations(organizations);
-};
+export const fetchOrganizations = async (
+ accessToken: string,
+ setOrganizations: (organizations: Organization[]) => void,
+) => {
+ const organizations = await organizationListCall(accessToken)
+ setOrganizations(organizations)
+}
const OrganizationsTable: React.FC<OrganizationsTableProps> = ({
organizations,
@@ -61,115 +64,106 @@ const OrganizationsTable: React.FC<OrganizationsTableProps> = ({
currentOrg,
guardrailsList = [],
setOrganizations,
- premiumUser
+ premiumUser,
}) => {
- const [selectedOrgId, setSelectedOrgId] = useState<string | null>(null);
- const [editOrg, setEditOrg] = useState(false);
- const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
- const [orgToDelete, setOrgToDelete] = useState<string | null>(null);
- const [isOrgModalVisible, setIsOrgModalVisible] = useState(false);
- const [form] = Form.useForm();
- const [expandedAccordions, setExpandedAccordions] = useState<Record<string, boolean>>({});
+ const [selectedOrgId, setSelectedOrgId] = useState<string | null>(null)
+ const [editOrg, setEditOrg] = useState(false)
+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
+ const [orgToDelete, setOrgToDelete] = useState<string | null>(null)
+ const [isOrgModalVisible, setIsOrgModalVisible] = useState(false)
+ const [form] = Form.useForm()
+ const [expandedAccordions, setExpandedAccordions] = useState<Record<string, boolean>>({})
useEffect(() => {
if (accessToken) {
- fetchOrganizations(accessToken, setOrganizations);
+ fetchOrganizations(accessToken, setOrganizations)
}
- }, [accessToken]);
+ }, [accessToken])
const handleDelete = (orgId: string | null) => {
- if (!orgId) return;
-
- setOrgToDelete(orgId);
- setIsDeleteModalOpen(true);
- };
+ if (!orgId) return
+
+ setOrgToDelete(orgId)
+ setIsDeleteModalOpen(true)
+ }
const confirmDelete = async () => {
- if (!orgToDelete || !accessToken) return;
+ if (!orgToDelete || !accessToken) return
try {
- await organizationDeleteCall(accessToken, orgToDelete);
- message.success('Organization deleted successfully');
+ await organizationDeleteCall(accessToken, orgToDelete)
+ message.success("Organization deleted successfully")
- setIsDeleteModalOpen(false);
- setOrgToDelete(null);
+ setIsDeleteModalOpen(false)
+ setOrgToDelete(null)
// Refresh organizations list
- fetchOrganizations(accessToken, setOrganizations);
+ fetchOrganizations(accessToken, setOrganizations)
} catch (error) {
- console.error('Error deleting organization:', error);
+ console.error("Error deleting organization:", error)
}
- };
+ }
const cancelDelete = () => {
- setIsDeleteModalOpen(false);
- setOrgToDelete(null);
- };
+ setIsDeleteModalOpen(false)
+ setOrgToDelete(null)
+ }
const handleCreate = async (values: any) => {
try {
- if (!accessToken) return;
+ if (!accessToken) return
- console.log(`values in organizations new create call: ${JSON.stringify(values)}`);
+ console.log(`values in organizations new create call: ${JSON.stringify(values)}`)
// Transform allowed_vector_store_ids and allowed_mcp_servers_and_groups into object_permission
if (
(values.allowed_vector_store_ids && values.allowed_vector_store_ids.length > 0) ||
- (values.allowed_mcp_servers_and_groups && (values.allowed_mcp_servers_and_groups.servers?.length > 0 || values.allowed_mcp_servers_and_groups.accessGroups?.length > 0))
+ (values.allowed_mcp_servers_and_groups &&
+ (values.allowed_mcp_servers_and_groups.servers?.length > 0 ||
+ values.allowed_mcp_servers_and_groups.accessGroups?.length > 0))
) {
- values.object_permission = {};
+ values.object_permission = {}
if (values.allowed_vector_store_ids && values.allowed_vector_store_ids.length > 0) {
- values.object_permission.vector_stores = values.allowed_vector_store_ids;
- delete values.allowed_vector_store_ids;
+ values.object_permission.vector_stores = values.allowed_vector_store_ids
+ delete values.allowed_vector_store_ids
}
if (values.allowed_mcp_servers_and_groups) {
if (values.allowed_mcp_servers_and_groups.servers?.length > 0) {
- values.object_permission.mcp_servers = values.allowed_mcp_servers_and_groups.servers;
+ values.object_permission.mcp_servers = values.allowed_mcp_servers_and_groups.servers
}
if (values.allowed_mcp_servers_and_groups.accessGroups?.length > 0) {
- values.object_permission.mcp_access_groups = values.allowed_mcp_servers_and_groups.accessGroups;
+ values.object_permission.mcp_access_groups = values.allowed_mcp_servers_and_groups.accessGroups
}
- delete values.allowed_mcp_servers_and_groups;
+ delete values.allowed_mcp_servers_and_groups
}
}
- await organizationCreateCall(accessToken, values);
- setIsOrgModalVisible(false);
- form.resetFields();
+ await organizationCreateCall(accessToken, values)
+ setIsOrgModalVisible(false)
+ form.resetFields()
// Refresh organizations list
- fetchOrganizations(accessToken, setOrganizations);
+ fetchOrganizations(accessToken, setOrganizations)
} catch (error) {
- console.error('Error creating organization:', error);
+ console.error("Error creating organization:", error)
}
- };
+ }
const handleCancel = () => {
- setIsOrgModalVisible(false);
- form.resetFields();
- };
+ setIsOrgModalVisible(false)
+ form.resetFields()
+ }
if (!premiumUser) {
return (
<div>
- <Text>This is a LiteLLM Enterprise feature, and requires a valid key to use. Get a trial key <a href="https://www.litellm.ai/#pricing" target="_blank" rel="noopener noreferrer">here</a>.</Text>
+ <Text>
+ This is a LiteLLM Enterprise feature, and requires a valid key to use. Get a trial key{" "}
+ <a href="https://www.litellm.ai/#pricing" target="_blank" rel="noopener noreferrer">
+ here
+ </a>
+ .
+ </Text>
</div>
- );
- }
-
- if (selectedOrgId) {
- return (
- <OrganizationInfoView
- organizationId={selectedOrgId}
- onClose={() => {
- setSelectedOrgId(null);
- setEditOrg(false);
- }}
- accessToken={accessToken}
- is_org_admin={true} // You'll need to implement proper org admin check
- is_proxy_admin={userRole === "Admin"}
- userModels={userModels}
- editOrg={editOrg}
- />
- );
+ )
}
return (
@@ -177,436 +171,331 @@ const OrganizationsTable: React.FC<OrganizationsTableProps> = ({
<Grid numItems={1} className="gap-2 p-8 w-full mt-2">
<Col numColSpan={1} className="flex flex-col gap-2">
{(userRole === "Admin" || userRole === "Org Admin") && (
- <>
- <Button
- className="w-fit"
- onClick={() => setIsOrgModalVisible(true)}
- >
- + Create New Organization
- </Button>
- <Modal
- title="Create Organization"
- visible={isOrgModalVisible}
- width={800}
- footer={null}
- onCancel={handleCancel}
- >
- <Form
- form={form}
- onFinish={handleCreate}
- labelCol={{ span: 8 }}
- wrapperCol={{ span: 16 }}
- labelAlign="left"
- >
- <Form.Item
- label="Organization Name"
- name="organization_alias"
- rules={[{ required: true, message: "Please input an organization name" }]}
- >
- <TextInput placeholder="" />
- </Form.Item>
- <Form.Item label="Models" name="models">
- <Select2
- mode="multiple"
- placeholder="Select models"
- style={{ width: "100%" }}
- >
- <Select2.Option key="all-proxy-models" value="all-proxy-models">
- All Proxy Models
- </Select2.Option>
- {userModels && userModels.length > 0 && userModels.map((model) => (
- <Select2.Option key={model} value={model}>
- {getModelDisplayName(model)}
- </Select2.Option>
- ))}
- </Select2>
- </Form.Item>
-
- <Form.Item label="Max Budget (USD)" name="max_budget">
- <NumericalInput step={0.01} precision={2} width={200} />
- </Form.Item>
- <Form.Item label="Reset Budget" name="budget_duration">
- <Select2 defaultValue={null} placeholder="n/a">
- <Select2.Option value="24h">daily</Select2.Option>
- <Select2.Option value="7d">weekly</Select2.Option>
- <Select2.Option value="30d">monthly</Select2.Option>
- </Select2>
- </Form.Item>
- <Form.Item label="Tokens per minute Limit (TPM)" name="tpm_limit">
- <NumericalInput step={1} width={400} />
- </Form.Item>
- <Form.Item label="Requests per minute Limit (RPM)" name="rpm_limit">
- <NumericalInput step={1} width={400} />
- </Form.Item>
-
- <Form.Item
- label={
- <span>
- Allowed Vector Stores{' '}
- <Tooltip title="Select which vector stores this organization can access by default. Leave empty for access to all vector stores">
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
- </Tooltip>
- </span>
- }
- name="allowed_vector_store_ids"
- className="mt-4"
- help="Select vector stores this organization can access. Leave empty for access to all vector stores"
- >
- <VectorStoreSelector
- onChange={(values) => 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>
- Allowed MCP Servers{' '}
- <Tooltip title="Select which MCP servers and access groups this organization can access by default.">
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
- </Tooltip>
- </span>
- }
- name="allowed_mcp_servers_and_groups"
- className="mt-4"
- help="Select MCP servers and access groups this organization can access."
- >
- <MCPServerSelector
- onChange={(values) => form.setFieldValue('allowed_mcp_servers_and_groups', values)}
- value={form.getFieldValue('allowed_mcp_servers_and_groups')}
- accessToken={accessToken || ''}
- placeholder="Select MCP servers and access groups (optional)"
- />
- </Form.Item>
-
- <Form.Item label="Metadata" name="metadata">
- <Input.TextArea rows={4} />
- </Form.Item>
-
- <div style={{ textAlign: "right", marginTop: "10px" }}>
- <Button type="submit">Create Organization</Button>
- </div>
- </Form>
- </Modal>
- </>
+ <Button className="w-fit" onClick={() => setIsOrgModalVisible(true)}>
+ + Create New Organization
+ </Button>
)}
+ {selectedOrgId ? (
+ <OrganizationInfoView
+ organizationId={selectedOrgId}
+ onClose={() => {
+ setSelectedOrgId(null)
+ setEditOrg(false)
+ }}
+ accessToken={accessToken}
+ is_org_admin={true} // You'll need to implement proper org admin check
+ is_proxy_admin={userRole === "Admin"}
+ userModels={userModels}
+ editOrg={editOrg}
+ />
+ ) : (
+ <TabGroup className="gap-2 h-[75vh] w-full">
+ <TabList className="flex justify-between mt-2 w-full items-center">
+ <div className="flex">
+ <Tab>Your Organizations</Tab>
+ </div>
+ <div className="flex items-center space-x-2">
+ {lastRefreshed && <Text>Last Refreshed: {lastRefreshed}</Text>}
+ <Icon
+ icon={RefreshIcon}
+ variant="shadow"
+ size="xs"
+ className="self-center"
+ onClick={handleRefreshClick}
+ />
+ </div>
+ </TabList>
+ <TabPanels>
+ <TabPanel>
+ <Text>Click on &ldquo;Organization ID&rdquo; to view organization details.</Text>
+ <Grid numItems={1} className="gap-2 pt-2 pb-2 h-[75vh] w-full mt-2">
+ <Col numColSpan={1}>
+ <Card className="w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]">
+ <Table>
+ <TableHead>
+ <TableRow>
+ <TableHeaderCell>Organization ID</TableHeaderCell>
+ <TableHeaderCell>Organization Name</TableHeaderCell>
+ <TableHeaderCell>Created</TableHeaderCell>
+ <TableHeaderCell>Spend (USD)</TableHeaderCell>
+ <TableHeaderCell>Budget (USD)</TableHeaderCell>
+ <TableHeaderCell>Models</TableHeaderCell>
+ <TableHeaderCell>TPM / RPM Limits</TableHeaderCell>
+ <TableHeaderCell>Info</TableHeaderCell>
+ <TableHeaderCell>Actions</TableHeaderCell>
+ </TableRow>
+ </TableHead>
- <TabGroup className="gap-2 h-[75vh] w-full">
- <TabList className="flex justify-between mt-2 w-full items-center">
- <div className="flex">
- <Tab>Your Organizations</Tab>
- </div>
- <div className="flex items-center space-x-2">
- {lastRefreshed && <Text>Last Refreshed: {lastRefreshed}</Text>}
- <Icon
- icon={RefreshIcon}
- variant="shadow"
- size="xs"
- className="self-center"
- onClick={handleRefreshClick}
- />
- </div>
- </TabList>
- <TabPanels>
- <TabPanel>
- <Text>
- Click on &ldquo;Organization ID&rdquo; to view organization details.
- </Text>
- <Grid numItems={1} className="gap-2 pt-2 pb-2 h-[75vh] w-full mt-2">
- <Col numColSpan={1}>
- <Card className="w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]">
- <Table>
- <TableHead>
- <TableRow>
- <TableHeaderCell>Organization ID</TableHeaderCell>
- <TableHeaderCell>Organization Name</TableHeaderCell>
- <TableHeaderCell>Created</TableHeaderCell>
- <TableHeaderCell>Spend (USD)</TableHeaderCell>
- <TableHeaderCell>Budget (USD)</TableHeaderCell>
- <TableHeaderCell>Models</TableHeaderCell>
- <TableHeaderCell>TPM / RPM Limits</TableHeaderCell>
- <TableHeaderCell>Info</TableHeaderCell>
- <TableHeaderCell>Actions</TableHeaderCell>
- </TableRow>
- </TableHead>
-
- <TableBody>
- {organizations && organizations.length > 0
- ? organizations
- .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
- .map((org: Organization) => (
- <TableRow key={org.organization_id}>
- <TableCell>
- <div className="overflow-hidden">
- <Tooltip title={org.organization_id}>
- <Button
- size="xs"
- variant="light"
- className="font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]"
- onClick={() => setSelectedOrgId(org.organization_id)}
- >
- {org.organization_id?.slice(0, 7)}...
- </Button>
- </Tooltip>
- </div>
- </TableCell>
- <TableCell>{org.organization_alias}</TableCell>
- <TableCell>
- {org.created_at ? new Date(org.created_at).toLocaleDateString() : "N/A"}
- </TableCell>
- <TableCell>{formatNumberWithCommas(org.spend, 4)}</TableCell>
- <TableCell>
- {org.litellm_budget_table?.max_budget !== null && org.litellm_budget_table?.max_budget !== undefined ? org.litellm_budget_table?.max_budget : "No limit"}
- </TableCell>
- <TableCell
- style={{
- maxWidth: "8-x",
- whiteSpace: "pre-wrap",
- overflow: "hidden",
- }}
- className={org.models.length > 3 ? "px-0" : ""}
- >
- <div className="flex flex-col">
- {Array.isArray(org.models) ? (
- <div className="flex flex-col">
- {org.models.length === 0 ? (
- <Badge size={"xs"} className="mb-1" color="red">
- <Text>All Proxy Models</Text>
- </Badge>
- ) : (
- <>
- <div className="flex items-start">
- {org.models.length > 3 && (
- <div>
- <Icon
- icon={expandedAccordions[org.organization_id || ''] ? ChevronDownIcon : ChevronRightIcon}
- className="cursor-pointer"
- size="xs"
- onClick={() => {
- setExpandedAccordions(prev => ({
- ...prev,
- [org.organization_id || '']: !prev[org.organization_id || '']
- }));
- }}
- />
- </div>
- )}
- <div className="flex flex-wrap gap-1">
- {org.models.slice(0, 3).map((model, index) => (
- model === "all-proxy-models" ? (
- <Badge
- key={index}
- size={"xs"}
- color="red"
- >
- <Text>All Proxy Models</Text>
- </Badge>
- ) : (
- <Badge
- key={index}
- size={"xs"}
- color="blue"
- >
- <Text>
- {model.length > 30
- ? `${getModelDisplayName(model).slice(0, 30)}...`
- : getModelDisplayName(model)}
- </Text>
- </Badge>
- )
- ))}
- {org.models.length > 3 && !expandedAccordions[org.organization_id || ''] && (
- <Badge size={"xs"} color="gray" className="cursor-pointer">
- <Text>+{org.models.length - 3} {org.models.length - 3 === 1 ? 'more model' : 'more models'}</Text>
+ <TableBody>
+ {organizations && organizations.length > 0
+ ? organizations
+ .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
+ .map((org: Organization) => (
+ <TableRow key={org.organization_id}>
+ <TableCell>
+ <div className="overflow-hidden">
+ <Tooltip title={org.organization_id}>
+ <Button
+ size="xs"
+ variant="light"
+ className="font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]"
+ onClick={() => setSelectedOrgId(org.organization_id)}
+ >
+ {org.organization_id?.slice(0, 7)}
+ ...
+ </Button>
+ </Tooltip>
+ </div>
+ </TableCell>
+ <TableCell>{org.organization_alias}</TableCell>
+ <TableCell>
+ {org.created_at ? new Date(org.created_at).toLocaleDateString() : "N/A"}
+ </TableCell>
+ <TableCell>{formatNumberWithCommas(org.spend, 4)}</TableCell>
+ <TableCell>
+ {org.litellm_budget_table?.max_budget !== null &&
+ org.litellm_budget_table?.max_budget !== undefined
+ ? org.litellm_budget_table?.max_budget
+ : "No limit"}
+ </TableCell>
+ <TableCell
+ style={{
+ maxWidth: "8-x",
+ whiteSpace: "pre-wrap",
+ overflow: "hidden",
+ }}
+ className={org.models.length > 3 ? "px-0" : ""}
+ >
+ <div className="flex flex-col">
+ {Array.isArray(org.models) ? (
+ <div className="flex flex-col">
+ {org.models.length === 0 ? (
+ <Badge size={"xs"} className="mb-1" color="red">
+ <Text>All Proxy Models</Text>
</Badge>
- )}
- {expandedAccordions[org.organization_id || ''] && (
- <div className="flex flex-wrap gap-1">
- {org.models.slice(3).map((model, index) => (
- model === "all-proxy-models" ? (
- <Badge
- key={index + 3}
- size={"xs"}
- color="red"
- >
- <Text>All Proxy Models</Text>
- </Badge>
- ) : (
- <Badge
- key={index + 3}
- size={"xs"}
- color="blue"
- >
- <Text>
- {model.length > 30
- ? `${getModelDisplayName(model).slice(0, 30)}...`
- : getModelDisplayName(model)}
- </Text>
- </Badge>
- )
- ))}
- </div>
+ ) : (
+ <>
+ <div className="flex items-start">
+ {org.models.length > 3 && (
+ <div>
+ <Icon
+ icon={
+ expandedAccordions[org.organization_id || ""]
+ ? ChevronDownIcon
+ : ChevronRightIcon
+ }
+ className="cursor-pointer"
+ size="xs"
+ onClick={() => {
+ setExpandedAccordions((prev) => ({
+ ...prev,
+ [org.organization_id || ""]:
+ !prev[org.organization_id || ""],
+ }))
+ }}
+ />
+ </div>
+ )}
+ <div className="flex flex-wrap gap-1">
+ {org.models.slice(0, 3).map((model, index) =>
+ model === "all-proxy-models" ? (
+ <Badge key={index} size={"xs"} color="red">
+ <Text>All Proxy Models</Text>
+ </Badge>
+ ) : (
+ <Badge key={index} size={"xs"} color="blue">
+ <Text>
+ {model.length > 30
+ ? `${getModelDisplayName(model).slice(0, 30)}...`
+ : getModelDisplayName(model)}
+ </Text>
+ </Badge>
+ ),
+ )}
+ {org.models.length > 3 &&
+ !expandedAccordions[org.organization_id || ""] && (
+ <Badge size={"xs"} color="gray" className="cursor-pointer">
+ <Text>
+ +{org.models.length - 3}{" "}
+ {org.models.length - 3 === 1
+ ? "more model"
+ : "more models"}
+ </Text>
+ </Badge>
+ )}
+ {expandedAccordions[org.organization_id || ""] && (
+ <div className="flex flex-wrap gap-1">
+ {org.models.slice(3).map((model, index) =>
+ model === "all-proxy-models" ? (
+ <Badge key={index + 3} size={"xs"} color="red">
+ <Text>All Proxy Models</Text>
+ </Badge>
+ ) : (
+ <Badge key={index + 3} size={"xs"} color="blue">
+ <Text>
+ {model.length > 30
+ ? `${getModelDisplayName(model).slice(0, 30)}...`
+ : getModelDisplayName(model)}
+ </Text>
+ </Badge>
+ ),
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ </>
)}
</div>
- </div>
- </>
- )}
- </div>
- ) : null}
- </div>
- </TableCell>
- <TableCell>
- <Text>
- TPM: {org.litellm_budget_table?.tpm_limit ? org.litellm_budget_table?.tpm_limit : "Unlimited"}
- <br />
- RPM: {org.litellm_budget_table?.rpm_limit ? org.litellm_budget_table?.rpm_limit : "Unlimited"}
- </Text>
- </TableCell>
- <TableCell>
- <Text>{org.members?.length || 0} Members</Text>
- </TableCell>
- <TableCell>
- {userRole === "Admin" && (
- <>
- <Icon
- icon={PencilAltIcon}
- size="sm"
- onClick={() => {
- setSelectedOrgId(org.organization_id);
- setEditOrg(true);
- }}
- />
- <Icon
- onClick={() => handleDelete(org.organization_id)}
- icon={TrashIcon}
- size="sm"
- />
- </>
- )}
- </TableCell>
- </TableRow>
- ))
- : null}
- </TableBody>
- </Table>
- </Card>
- </Col>
- {(userRole === "Admin" || userRole === "Org Admin") && (
- <Col numColSpan={1}>
- <Modal
- title="Create Organization"
- visible={isOrgModalVisible}
- width={800}
- footer={null}
- onCancel={handleCancel}
- >
- <Form
- form={form}
- onFinish={handleCreate}
- labelCol={{ span: 8 }}
- wrapperCol={{ span: 16 }}
- labelAlign="left"
- >
- <Form.Item
- label="Organization Name"
- name="organization_alias"
- rules={[{ required: true, message: "Please input an organization name" }]}
- >
- <TextInput placeholder="" />
- </Form.Item>
- <Form.Item label="Models" name="models">
- <Select2
- mode="multiple"
- placeholder="Select models"
- style={{ width: "100%" }}
- >
- <Select2.Option key="all-proxy-models" value="all-proxy-models">
- All Proxy Models
- </Select2.Option>
- {userModels && userModels.length > 0 && userModels.map((model) => (
- <Select2.Option key={model} value={model}>
- {getModelDisplayName(model)}
- </Select2.Option>
- ))}
- </Select2>
- </Form.Item>
+ ) : null}
+ </div>
+ </TableCell>
+ <TableCell>
+ <Text>
+ TPM:{" "}
+ {org.litellm_budget_table?.tpm_limit
+ ? org.litellm_budget_table?.tpm_limit
+ : "Unlimited"}
+ <br />
+ RPM:{" "}
+ {org.litellm_budget_table?.rpm_limit
+ ? org.litellm_budget_table?.rpm_limit
+ : "Unlimited"}
+ </Text>
+ </TableCell>
+ <TableCell>
+ <Text>{org.members?.length || 0} Members</Text>
+ </TableCell>
+ <TableCell>
+ {userRole === "Admin" && (
+ <>
+ <Icon
+ icon={PencilAltIcon}
+ size="sm"
+ onClick={() => {
+ setSelectedOrgId(org.organization_id)
+ setEditOrg(true)
+ }}
+ />
+ <Icon
+ onClick={() => handleDelete(org.organization_id)}
+ icon={TrashIcon}
+ size="sm"
+ />
+ </>
+ )}
+ </TableCell>
+ </TableRow>
+ ))
+ : null}
+ </TableBody>
+ </Table>
+ </Card>
+ </Col>
+ </Grid>
+ </TabPanel>
+ </TabPanels>
+ </TabGroup>
+ )}
+ </Col>
+ </Grid>
+ <Modal title="Create Organization" visible={isOrgModalVisible} width={800} footer={null} onCancel={handleCancel}>
+ <Form form={form} onFinish={handleCreate} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} labelAlign="left">
+ <Form.Item
+ label="Organization Name"
+ name="organization_alias"
+ rules={[
+ {
+ required: true,
+ message: "Please input an organization name",
+ },
+ ]}
+ >
+ <TextInput placeholder="" />
+ </Form.Item>
+ <Form.Item label="Models" name="models">
+ <Select2 mode="multiple" placeholder="Select models" style={{ width: "100%" }}>
+ <Select2.Option key="all-proxy-models" value="all-proxy-models">
+ All Proxy Models
+ </Select2.Option>
+ {userModels &&
+ userModels.length > 0 &&
+ userModels.map((model) => (
+ <Select2.Option key={model} value={model}>
+ {getModelDisplayName(model)}
+ </Select2.Option>
+ ))}
+ </Select2>
+ </Form.Item>
- <Form.Item label="Max Budget (USD)" name="max_budget">
- <NumericalInput step={0.01} precision={2} width={200} />
- </Form.Item>
- <Form.Item label="Reset Budget" name="budget_duration">
- <Select2 defaultValue={null} placeholder="n/a">
- <Select2.Option value="24h">daily</Select2.Option>
- <Select2.Option value="7d">weekly</Select2.Option>
- <Select2.Option value="30d">monthly</Select2.Option>
- </Select2>
- </Form.Item>
- <Form.Item label="Tokens per minute Limit (TPM)" name="tpm_limit">
- <NumericalInput step={1} width={400} />
- </Form.Item>
- <Form.Item label="Requests per minute Limit (RPM)" name="rpm_limit">
- <NumericalInput step={1} width={400} />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Allowed Vector Stores{' '}
- <Tooltip title="Select which vector stores this organization can access by default. Leave empty for access to all vector stores">
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
- </Tooltip>
- </span>
- }
- name="allowed_vector_store_ids"
- className="mt-4"
- help="Select vector stores this organization can access. Leave empty for access to all vector stores"
- >
- <VectorStoreSelector
- onChange={(values) => 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>
- Allowed MCP Servers{' '}
- <Tooltip title="Select which MCP servers and access groups this organization can access by default.">
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
- </Tooltip>
- </span>
- }
- name="allowed_mcp_servers_and_groups"
- className="mt-4"
- help="Select MCP servers and access groups this organization can access."
- >
- <MCPServerSelector
- onChange={(values) => form.setFieldValue('allowed_mcp_servers_and_groups', values)}
- value={form.getFieldValue('allowed_mcp_servers_and_groups')}
- accessToken={accessToken || ''}
- placeholder="Select MCP servers and access groups (optional)"
- />
- </Form.Item>
+ <Form.Item label="Max Budget (USD)" name="max_budget">
+ <NumericalInput step={0.01} precision={2} width={200} />
+ </Form.Item>
+ <Form.Item label="Reset Budget" name="budget_duration">
+ <Select2 defaultValue={null} placeholder="n/a">
+ <Select2.Option value="24h">daily</Select2.Option>
+ <Select2.Option value="7d">weekly</Select2.Option>
+ <Select2.Option value="30d">monthly</Select2.Option>
+ </Select2>
+ </Form.Item>
+ <Form.Item label="Tokens per minute Limit (TPM)" name="tpm_limit">
+ <NumericalInput step={1} width={400} />
+ </Form.Item>
+ <Form.Item label="Requests per minute Limit (RPM)" name="rpm_limit">
+ <NumericalInput step={1} width={400} />
+ </Form.Item>
- <Form.Item label="Metadata" name="metadata">
- <Input.TextArea rows={4} />
- </Form.Item>
+ <Form.Item
+ label={
+ <span>
+ Allowed Vector Stores{" "}
+ <Tooltip title="Select which vector stores this organization can access by default. Leave empty for access to all vector stores">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="allowed_vector_store_ids"
+ className="mt-4"
+ help="Select vector stores this organization can access. Leave empty for access to all vector stores"
+ >
+ <VectorStoreSelector
+ onChange={(values) => form.setFieldValue("allowed_vector_store_ids", values)}
+ value={form.getFieldValue("allowed_vector_store_ids")}
+ accessToken={accessToken || ""}
+ placeholder="Select vector stores (optional)"
+ />
+ </Form.Item>
- <div style={{ textAlign: "right", marginTop: "10px" }}>
- <Button type="submit">Create Organization</Button>
- </div>
- </Form>
- </Modal>
- </Col>
- )}
- </Grid>
- </TabPanel>
- </TabPanels>
- </TabGroup>
- </Col>
- </Grid>
+ <Form.Item
+ label={
+ <span>
+ Allowed MCP Servers{" "}
+ <Tooltip title="Select which MCP servers and access groups this organization can access by default.">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="allowed_mcp_servers_and_groups"
+ className="mt-4"
+ help="Select MCP servers and access groups this organization can access."
+ >
+ <MCPServerSelector
+ onChange={(values) => form.setFieldValue("allowed_mcp_servers_and_groups", values)}
+ value={form.getFieldValue("allowed_mcp_servers_and_groups")}
+ accessToken={accessToken || ""}
+ placeholder="Select MCP servers and access groups (optional)"
+ />
+ </Form.Item>
+
+ <Form.Item label="Metadata" name="metadata">
+ <Input.TextArea rows={4} />
+ </Form.Item>
+
+ <div style={{ textAlign: "right", marginTop: "10px" }}>
+ <Button type="submit">Create Organization</Button>
+ </div>
+ </Form>
+ </Modal>
{isDeleteModalOpen ? (
<div className="fixed z-10 inset-0 overflow-y-auto">
@@ -623,13 +512,9 @@ const OrganizationsTable: React.FC<OrganizationsTableProps> = ({
<div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div className="sm:flex sm:items-start">
<div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
- <h3 className="text-lg leading-6 font-medium text-gray-900">
- Delete Organization
- </h3>
+ <h3 className="text-lg leading-6 font-medium text-gray-900">Delete Organization</h3>
<div className="mt-2">
- <p className="text-sm text-gray-500">
- Are you sure you want to delete this organization?
- </p>
+ <p className="text-sm text-gray-500">Are you sure you want to delete this organization?</p>
</div>
</div>
</div>
@@ -643,10 +528,11 @@ const OrganizationsTable: React.FC<OrganizationsTableProps> = ({
</div>
</div>
</div>
- ) : <></>}
-
+ ) : (
+ <></>
+ )}
</div>
- );
-};
+ )
+}
-export default OrganizationsTable;
\ No newline at end of file
+export default OrganizationsTable
diff --git a/ui/litellm-dashboard/src/components/team/team_info.tsx b/ui/litellm-dashboard/src/components/team/team_info.tsx
index 8abcc3925cd..c2b4a402f75 100644
--- a/ui/litellm-dashboard/src/components/team/team_info.tsx
+++ b/ui/litellm-dashboard/src/components/team/team_info.tsx
@@ -18,17 +18,27 @@ import {
TableHeaderCell,
TableBody,
Table,
- Icon
+ Icon,
} from "@tremor/react";
import TeamMembersComponent from "./team_member_view";
import MemberPermissions from "./member_permissions";
-import { teamInfoCall, teamMemberDeleteCall, teamMemberAddCall, teamMemberUpdateCall, Member, teamUpdateCall } from "@/components/networking";
+import {
+ teamInfoCall,
+ teamMemberDeleteCall,
+ teamMemberAddCall,
+ teamMemberUpdateCall,
+ Member,
+ teamUpdateCall,
+} from "@/components/networking";
import { Button, Form, Input, Select, message, Tooltip } from "antd";
-import { InfoCircleOutlined } from '@ant-design/icons';
+import { InfoCircleOutlined } from "@ant-design/icons";
+import { Select as Select2 } from "antd";
import {
- Select as Select2,
-} from "antd";
-import { PencilAltIcon, PlusIcon, TrashIcon } from "@heroicons/react/outline";
+ ArrowLeftIcon,
+ PencilAltIcon,
+ PlusIcon,
+ TrashIcon,
+} from "@heroicons/react/outline";
import MemberModal from "./edit_membership";
import UserSearchModal from "@/components/common_components/user_search_modal";
import { getModelDisplayName } from "../key_team_helpers/fetch_available_models_team_key";
@@ -110,23 +120,26 @@ export interface TeamInfoProps {
premiumUser?: boolean;
}
-const TeamInfoView: React.FC<TeamInfoProps> = ({
- teamId,
- onClose,
- accessToken,
- is_team_admin,
+const TeamInfoView: React.FC<TeamInfoProps> = ({
+ teamId,
+ onClose,
+ accessToken,
+ is_team_admin,
is_proxy_admin,
userModels,
editTeam,
premiumUser = false,
- onUpdate
+ onUpdate,
}) => {
const [teamData, setTeamData] = useState<TeamData | null>(null);
const [loading, setLoading] = useState(true);
const [isAddMemberModalVisible, setIsAddMemberModalVisible] = useState(false);
const [form] = Form.useForm();
- const [isEditMemberModalVisible, setIsEditMemberModalVisible] = useState(false);
- const [selectedEditMember, setSelectedEditMember] = useState<Member | null>(null);
+ const [isEditMemberModalVisible, setIsEditMemberModalVisible] =
+ useState(false);
+ const [selectedEditMember, setSelectedEditMember] = useState<Member | null>(
+ null
+ );
const [isEditing, setIsEditing] = useState(false);
const [mcpAccessGroups, setMcpAccessGroups] = useState<string[]>([]);
const [mcpAccessGroupsLoaded, setMcpAccessGroupsLoaded] = useState(false);
@@ -168,41 +181,43 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
const handleMemberCreate = async (values: any) => {
try {
if (accessToken == null) return;
-
+
const member: Member = {
user_email: values.user_email,
user_id: values.user_id,
role: values.role,
};
-
+
await teamMemberAddCall(accessToken, teamId, member);
-
+
message.success("Team member added successfully");
setIsAddMemberModalVisible(false);
form.resetFields();
-
+
// Fetch updated team info
const updatedTeamData = await teamInfoCall(accessToken, teamId);
setTeamData(updatedTeamData);
-
+
// Notify parent component of the update
onUpdate(updatedTeamData);
} catch (error: any) {
let errMsg = "Failed to add team member";
-
- if (error?.raw?.detail?.error?.includes("Assigning team admins is a premium feature")) {
- errMsg = "Assigning admins is an enterprise-only feature. Please upgrade your LiteLLM plan to enable this.";
+
+ if (
+ error?.raw?.detail?.error?.includes(
+ "Assigning team admins is a premium feature"
+ )
+ ) {
+ errMsg =
+ "Assigning admins is an enterprise-only feature. Please upgrade your LiteLLM plan to enable this.";
} else if (error?.message) {
errMsg = error.message;
}
-
+
message.error(errMsg);
console.error("Error adding team member:", error);
}
};
-
-
-
const handleMemberUpdate = async (values: any) => {
try {
@@ -214,24 +229,29 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
user_email: values.user_email,
user_id: values.user_id,
role: values.role,
- }
+ };
message.destroy(); // Remove all existing toasts
await teamMemberUpdateCall(accessToken, teamId, member);
message.success("Team member updated successfully");
setIsEditMemberModalVisible(false);
-
+
// Fetch updated team info
const updatedTeamData = await teamInfoCall(accessToken, teamId);
setTeamData(updatedTeamData);
-
+
// Notify parent component of the update
onUpdate(updatedTeamData);
} catch (error: any) {
let errMsg = "Failed to update team member";
- if (error?.raw?.detail?.includes("Assigning team admins is a premium feature")) {
- errMsg = "Assigning admins is an enterprise-only feature. Please upgrade your LiteLLM plan to enable this.";
+ if (
+ error?.raw?.detail?.includes(
+ "Assigning team admins is a premium feature"
+ )
+ ) {
+ errMsg =
+ "Assigning admins is an enterprise-only feature. Please upgrade your LiteLLM plan to enable this.";
} else if (error?.message) {
errMsg = error.message;
}
@@ -243,7 +263,6 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
console.error("Error updating team member:", error);
}
};
-
const handleMemberDelete = async (member: Member) => {
try {
@@ -254,11 +273,11 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
await teamMemberDeleteCall(accessToken, teamId, member);
message.success("Team member removed successfully");
-
+
// Fetch updated team info
const updatedTeamData = await teamInfoCall(accessToken, teamId);
setTeamData(updatedTeamData);
-
+
// Notify parent component of the update
onUpdate(updatedTeamData);
} catch (error) {
@@ -290,7 +309,7 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
metadata: {
...parsedMetadata,
guardrails: values.guardrails || [],
- logging: values.logging_settings || []
+ logging: values.logging_settings || [],
},
organization_id: values.organization_id,
};
@@ -304,8 +323,14 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
}
// Handle object_permission updates
- const { servers, accessGroups } = values.mcp_servers_and_groups || { servers: [], accessGroups: [] };
- if ((servers && servers.length > 0) || (accessGroups && accessGroups.length > 0)) {
+ const { servers, accessGroups } = values.mcp_servers_and_groups || {
+ servers: [],
+ accessGroups: [],
+ };
+ if (
+ (servers && servers.length > 0) ||
+ (accessGroups && accessGroups.length > 0)
+ ) {
updateData.object_permission = {};
if (servers && servers.length > 0) {
updateData.object_permission.mcp_servers = servers;
@@ -315,9 +340,9 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
}
}
delete values.mcp_servers_and_groups;
-
+
const response = await teamUpdateCall(accessToken, updateData);
-
+
message.success("Team settings updated successfully");
setIsEditing(false);
fetchTeamInfo();
@@ -340,7 +365,14 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
<div className="p-4">
<div className="flex justify-between items-center mb-6">
<div>
- <Button onClick={onClose} className="mb-4">← Back</Button>
+ <TremorButton
+ icon={ArrowLeftIcon}
+ variant="light"
+ onClick={onClose}
+ className="mb-4"
+ >
+ Back to Teams
+ </TremorButton>
<Title>{info.team_alias}</Title>
<Text className="text-gray-500 font-mono">{info.team_id}</Text>
</div>
@@ -350,11 +382,13 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
<TabList className="mb-4">
{[
<Tab key="overview">Overview</Tab>,
- ...(canEditTeam ? [
- <Tab key="members">Members</Tab>,
- <Tab key="member-permissions">Member Permissions</Tab>,
- <Tab key="settings">Settings</Tab>
- ] : [])
+ ...(canEditTeam
+ ? [
+ <Tab key="members">Members</Tab>,
+ <Tab key="member-permissions">Member Permissions</Tab>,
+ <Tab key="settings">Settings</Tab>,
+ ]
+ : []),
]}
</TabList>
@@ -366,13 +400,26 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
<Text>Budget Status</Text>
<div className="mt-2">
<Title>${formatNumberWithCommas(info.spend, 4)}</Title>
- <Text>of {info.max_budget === null ? "Unlimited" : `$${formatNumberWithCommas(info.max_budget, 4)}`}</Text>
+ <Text>
+ of{" "}
+ {info.max_budget === null
+ ? "Unlimited"
+ : `$${formatNumberWithCommas(info.max_budget, 4)}`}
+ </Text>
{info.budget_duration && (
- <Text className="text-gray-500">Reset: {info.budget_duration}</Text>
+ <Text className="text-gray-500">
+ Reset: {info.budget_duration}
+ </Text>
)}
- <br/>
+ <br />
{info.team_member_budget_table && (
- <Text className="text-gray-500">Team Member Budget: ${formatNumberWithCommas(info.team_member_budget_table.max_budget, 4)}</Text>
+ <Text className="text-gray-500">
+ Team Member Budget: $
+ {formatNumberWithCommas(
+ info.team_member_budget_table.max_budget,
+ 4
+ )}
+ </Text>
)}
</div>
</Card>
@@ -380,10 +427,12 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
<Card>
<Text>Rate Limits</Text>
<div className="mt-2">
- <Text>TPM: {info.tpm_limit || 'Unlimited'}</Text>
- <Text>RPM: {info.rpm_limit || 'Unlimited'}</Text>
+ <Text>TPM: {info.tpm_limit || "Unlimited"}</Text>
+ <Text>RPM: {info.rpm_limit || "Unlimited"}</Text>
{info.max_parallel_requests && (
- <Text>Max Parallel Requests: {info.max_parallel_requests}</Text>
+ <Text>
+ Max Parallel Requests: {info.max_parallel_requests}
+ </Text>
)}
</div>
</Card>
@@ -403,13 +452,13 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
</div>
</Card>
- <ObjectPermissionsView
- objectPermission={info.object_permission}
+ <ObjectPermissionsView
+ objectPermission={info.object_permission}
variant="card"
accessToken={accessToken}
/>
- <LoggingSettingsView
+ <LoggingSettingsView
loggingConfigs={info.metadata?.logging || []}
variant="card"
/>
@@ -431,7 +480,7 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
{/* Member Permissions Panel */}
{canEditTeam && (
<TabPanel>
- <MemberPermissions
+ <MemberPermissions
teamId={teamId}
accessToken={accessToken}
canEditTeam={canEditTeam}
@@ -444,10 +493,8 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
<Card className="overflow-y-auto max-h-[65vh]">
<div className="flex justify-between items-center mb-4">
<Title>Team Settings</Title>
- {(canEditTeam && !isEditing) && (
- <TremorButton
- onClick={() => setIsEditing(true)}
- >
+ {canEditTeam && !isEditing && (
+ <TremorButton onClick={() => setIsEditing(true)}>
Edit Settings
</TremorButton>
)}
@@ -467,31 +514,39 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
budget_duration: info.budget_duration,
guardrails: info.metadata?.guardrails || [],
metadata: info.metadata
- ? JSON.stringify((({ logging, ...rest }) => rest)(info.metadata), null, 2)
+ ? JSON.stringify(
+ (({ logging, ...rest }) => rest)(info.metadata),
+ null,
+ 2
+ )
: "",
logging_settings: info.metadata?.logging || [],
organization_id: info.organization_id,
vector_stores: info.object_permission?.vector_stores || [],
mcp_servers: info.object_permission?.mcp_servers || [],
- mcp_access_groups: info.object_permission?.mcp_servers || [],
- mcp_servers_and_groups: info.object_permission?.mcp_servers || []
+ mcp_access_groups:
+ info.object_permission?.mcp_servers || [],
+ mcp_servers_and_groups:
+ info.object_permission?.mcp_servers || [],
}}
layout="vertical"
>
<Form.Item
label="Team Name"
name="team_alias"
- rules={[{ required: true, message: "Please input a team name" }]}
+ rules={[
+ { required: true, message: "Please input a team name" },
+ ]}
>
- <Input type=""/>
+ <Input type="" />
</Form.Item>
-
+
<Form.Item label="Models" name="models">
- <Select
- mode="multiple"
- placeholder="Select models"
- >
- <Select.Option key="all-proxy-models" value="all-proxy-models">
+ <Select mode="multiple" placeholder="Select models">
+ <Select.Option
+ key="all-proxy-models"
+ value="all-proxy-models"
+ >
All Proxy Models
</Select.Option>
{Array.from(new Set(userModels)).map((model, idx) => (
@@ -503,14 +558,30 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
</Form.Item>
<Form.Item label="Max Budget (USD)" name="max_budget">
- <NumericalInput step={0.01} precision={2} style={{ width: "100%" }} />
+ <NumericalInput
+ step={0.01}
+ precision={2}
+ style={{ width: "100%" }}
+ />
</Form.Item>
- <Form.Item label="Team Member Budget (USD)" name="team_member_budget" tooltip="This is the individual budget for a user in the team.">
- <NumericalInput step={0.01} precision={2} style={{ width: "100%" }} />
+ <Form.Item
+ label="Team Member Budget (USD)"
+ name="team_member_budget"
+ tooltip="This is the individual budget for a user in the team."
+ >
+ <NumericalInput
+ step={0.01}
+ precision={2}
+ style={{ width: "100%" }}
+ />
</Form.Item>
- <Form.Item label="Team Member Key Duration" name="team_member_key_duration" tooltip="Set a limit to the duration of a team member's key.">
+ <Form.Item
+ label="Team Member Key Duration"
+ name="team_member_key_duration"
+ tooltip="Set a limit to the duration of a team member's key."
+ >
<Select placeholder="n/a">
<Select.Option value="1d">1 day</Select.Option>
<Select.Option value="1w">1 week</Select.Option>
@@ -518,7 +589,6 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
</Select>
</Form.Item>
-
<Form.Item label="Reset Budget" name="budget_duration">
<Select placeholder="n/a">
<Select.Option value="24h">daily</Select.Option>
@@ -527,26 +597,32 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
</Select>
</Form.Item>
- <Form.Item label="Tokens per minute Limit (TPM)" name="tpm_limit">
+ <Form.Item
+ label="Tokens per minute Limit (TPM)"
+ name="tpm_limit"
+ >
<NumericalInput step={1} style={{ width: "100%" }} />
</Form.Item>
- <Form.Item label="Requests per minute Limit (RPM)" name="rpm_limit">
+ <Form.Item
+ label="Requests per minute Limit (RPM)"
+ name="rpm_limit"
+ >
<NumericalInput step={1} style={{ width: "100%" }} />
</Form.Item>
<Form.Item
label={
<span>
- Guardrails{' '}
+ Guardrails{" "}
<Tooltip title="Setup your first guardrail">
- <a
- href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"
- target="_blank"
+ <a
+ href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"
+ target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
>
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
</a>
</Tooltip>
</span>
@@ -562,45 +638,54 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
<Form.Item label="Vector Stores" name="vector_stores">
<VectorStoreSelector
- onChange={(values) => form.setFieldValue('vector_stores', values)}
- value={form.getFieldValue('vector_stores')}
+ onChange={(values) =>
+ form.setFieldValue("vector_stores", values)
+ }
+ value={form.getFieldValue("vector_stores")}
accessToken={accessToken || ""}
placeholder="Select vector stores"
/>
</Form.Item>
- <Form.Item label="MCP Servers / Access Groups" name="mcp_servers_and_groups">
+ <Form.Item
+ label="MCP Servers / Access Groups"
+ name="mcp_servers_and_groups"
+ >
<MCPServerSelector
- onChange={val => form.setFieldValue('mcp_servers_and_groups', val)}
- value={form.getFieldValue('mcp_servers_and_groups')}
- accessToken={accessToken || ''}
+ onChange={(val) =>
+ form.setFieldValue("mcp_servers_and_groups", val)
+ }
+ value={form.getFieldValue("mcp_servers_and_groups")}
+ accessToken={accessToken || ""}
placeholder="Select MCP servers or access groups (optional)"
/>
</Form.Item>
<Form.Item label="Organization ID" name="organization_id">
- <Input type=""/>
+ <Input type="" />
</Form.Item>
<Form.Item label="Logging Settings" name="logging_settings">
<EditLoggingSettings
- value={form.getFieldValue('logging_settings')}
- onChange={(values) => form.setFieldValue('logging_settings', values)}
+ value={form.getFieldValue("logging_settings")}
+ onChange={(values) =>
+ form.setFieldValue("logging_settings", values)
+ }
/>
</Form.Item>
-
<Form.Item label="Metadata" name="metadata">
<Input.TextArea rows={10} />
</Form.Item>
-
+
<div className="sticky z-10 bg-white p-4 border-t border-gray-200 bottom-[-1.5rem] inset-x-[-1.5rem]">
<div className="flex justify-end items-center gap-2">
- <Button htmlType="button" onClick={() => setIsEditing(false)}>
+ <Button
+ htmlType="button"
+ onClick={() => setIsEditing(false)}
+ >
Cancel
</Button>
- <TremorButton type="submit">
- Save Changes
- </TremorButton>
+ <TremorButton type="submit">Save Changes</TremorButton>
</div>
</div>
</Form>
@@ -630,23 +715,34 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
</div>
<div>
<Text className="font-medium">Rate Limits</Text>
- <div>TPM: {info.tpm_limit || 'Unlimited'}</div>
- <div>RPM: {info.rpm_limit || 'Unlimited'}</div>
+ <div>TPM: {info.tpm_limit || "Unlimited"}</div>
+ <div>RPM: {info.rpm_limit || "Unlimited"}</div>
</div>
<div>
<Text className="font-medium">Team Budget</Text>
- <div>Max Budget: {info.max_budget !== null ? `$${formatNumberWithCommas(info.max_budget, 4)}` : 'No Limit'}</div>
- <div>Budget Reset: {info.budget_duration || 'Never'}</div>
+ <div>
+ Max Budget:{" "}
+ {info.max_budget !== null
+ ? `$${formatNumberWithCommas(info.max_budget, 4)}`
+ : "No Limit"}
+ </div>
+ <div>Budget Reset: {info.budget_duration || "Never"}</div>
</div>
<div>
<Text className="font-medium">
- Team Member Settings{' '}
+ Team Member Settings{" "}
<Tooltip title="These are limits on individual team members">
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
</Tooltip>
</Text>
- <div>Max Budget: {info.team_member_budget_table?.max_budget || 'No Limit'}</div>
- <div>Key Duration: {info.metadata?.team_member_key_duration || 'No Limit'}</div>
+ <div>
+ Max Budget:{" "}
+ {info.team_member_budget_table?.max_budget || "No Limit"}
+ </div>
+ <div>
+ Key Duration:{" "}
+ {info.metadata?.team_member_key_duration || "No Limit"}
+ </div>
</div>
<div>
<Text className="font-medium">Organization ID</Text>
@@ -654,19 +750,19 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
</div>
<div>
<Text className="font-medium">Status</Text>
- <Badge color={info.blocked ? 'red' : 'green'}>
- {info.blocked ? 'Blocked' : 'Active'}
+ <Badge color={info.blocked ? "red" : "green"}>
+ {info.blocked ? "Blocked" : "Active"}
</Badge>
</div>
- <ObjectPermissionsView
- objectPermission={info.object_permission}
+ <ObjectPermissionsView
+ objectPermission={info.object_permission}
variant="inline"
className="pt-4 border-t border-gray-200"
accessToken={accessToken}
/>
- <LoggingSettingsView
+ <LoggingSettingsView
loggingConfigs={info.metadata?.logging || []}
variant="inline"
className="pt-4 border-t border-gray-200"
@@ -690,8 +786,8 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
showUserId: true,
roleOptions: [
{ label: "Admin", value: "admin" },
- { label: "User", value: "user" }
- ]
+ { label: "User", value: "user" },
+ ],
}}
/>
@@ -705,4 +801,4 @@ const TeamInfoView: React.FC<TeamInfoProps> = ({
);
};
-export default TeamInfoView;
\ No newline at end of file
+export default TeamInfoView;
diff --git a/ui/litellm-dashboard/src/components/teams.tsx b/ui/litellm-dashboard/src/components/teams.tsx
index b7db95a39cc..ef6ecd42e1d 100644
--- a/ui/litellm-dashboard/src/components/teams.tsx
+++ b/ui/litellm-dashboard/src/components/teams.tsx
@@ -1,7 +1,14 @@
import React, { useState, useEffect } from "react";
import Link from "next/link";
import { Typography } from "antd";
-import { teamDeleteCall, teamUpdateCall, teamInfoCall, Organization, DEFAULT_ORGANIZATION, fetchMCPAccessGroups } from "./networking";
+import {
+ teamDeleteCall,
+ teamUpdateCall,
+ teamInfoCall,
+ Organization,
+ DEFAULT_ORGANIZATION,
+ fetchMCPAccessGroups,
+} from "./networking";
import TeamMemberModal from "@/components/team/edit_membership";
import { fetchTeams } from "./common_components/fetch_teams";
import {
@@ -12,7 +19,7 @@ import {
StatusOnlineIcon,
TrashIcon,
ChevronDownIcon,
- ChevronRightIcon
+ ChevronRightIcon,
} from "@heroicons/react/outline";
import {
Button as Button2,
@@ -21,12 +28,16 @@ import {
Input,
Select as Select2,
message,
- Tooltip
+ Tooltip,
} from "antd";
import NumericalInput from "./shared/numerical_input";
-import { fetchAvailableModelsForTeamOrKey, getModelDisplayName, unfurlWildcardModelsInList } from "./key_team_helpers/fetch_available_models_team_key";
+import {
+ fetchAvailableModelsForTeamOrKey,
+ getModelDisplayName,
+ unfurlWildcardModelsInList,
+} from "./key_team_helpers/fetch_available_models_team_key";
import { Select, SelectItem } from "@tremor/react";
-import { InfoCircleOutlined } from '@ant-design/icons';
+import { InfoCircleOutlined } from "@ant-design/icons";
import { getGuardrailsList } from "./networking";
import TeamInfoView, { TeamData } from "@/components/team/team_info";
import TeamSSOSettings from "@/components/TeamSSOSettings";
@@ -53,7 +64,7 @@ import {
TabList,
TabPanel,
TabPanels,
- Tab
+ Tab,
} from "@tremor/react";
import { CogIcon } from "@heroicons/react/outline";
import AvailableTeamsPanel from "@/components/team/available_teams";
@@ -80,7 +91,7 @@ interface FilterState {
team_alias: string;
organization_id: string;
sort_by: string;
- sort_order: 'asc' | 'desc';
+ sort_order: "asc" | "desc";
}
interface EditTeamModalProps {
@@ -96,7 +107,7 @@ import {
teamMemberUpdateCall,
Member,
modelAvailableCall,
- v2TeamListCall
+ v2TeamListCall,
} from "./networking";
import { updateExistingKeys } from "@/utils/dataUtils";
@@ -109,7 +120,10 @@ interface PerTeamInfo {
team_info: TeamInfo;
}
-const getOrganizationModels = (organization: Organization | null, userModels: string[]) => {
+const getOrganizationModels = (
+ organization: Organization | null,
+ userModels: string[]
+) => {
let tempModelsToPick = [];
if (organization) {
@@ -126,7 +140,7 @@ const getOrganizationModels = (organization: Organization | null, userModels: st
}
return unfurlWildcardModelsInList(tempModelsToPick, userModels);
-}
+};
const Teams: React.FC<TeamProps> = ({
teams,
@@ -136,27 +150,28 @@ const Teams: React.FC<TeamProps> = ({
userID,
userRole,
organizations,
- premiumUser = false
+ premiumUser = false,
}) => {
const [lastRefreshed, setLastRefreshed] = useState("");
const [currentOrg, setCurrentOrg] = useState<Organization | null>(null);
- const [currentOrgForCreateTeam, setCurrentOrgForCreateTeam] = useState<Organization | null>(null);
+ const [currentOrgForCreateTeam, setCurrentOrgForCreateTeam] =
+ useState<Organization | null>(null);
const [showFilters, setShowFilters] = useState(false);
const [filters, setFilters] = useState<FilterState>({
team_id: "",
team_alias: "",
organization_id: "",
sort_by: "created_at",
- sort_order: "desc"
+ sort_order: "desc",
});
useEffect(() => {
- console.log(`inside useeffect - ${lastRefreshed}`)
+ console.log(`inside useeffect - ${lastRefreshed}`);
if (accessToken) {
// Call your function here
- fetchTeams(accessToken, userID, userRole, currentOrg, setTeams)
+ fetchTeams(accessToken, userID, userRole, currentOrg, setTeams);
}
- handleRefreshClick()
+ handleRefreshClick();
}, [lastRefreshed]);
const [form] = Form.useForm();
@@ -165,24 +180,27 @@ const Teams: React.FC<TeamProps> = ({
const [value, setValue] = useState("");
const [editModalVisible, setEditModalVisible] = useState(false);
- const [selectedTeam, setSelectedTeam] = useState<null | any>(
- null
- );
+ const [selectedTeam, setSelectedTeam] = useState<null | any>(null);
const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null);
const [editTeam, setEditTeam] = useState<boolean>(false);
const [isTeamModalVisible, setIsTeamModalVisible] = useState(false);
const [isAddMemberModalVisible, setIsAddMemberModalVisible] = useState(false);
- const [isEditMemberModalVisible, setIsEditMemberModalVisible] = useState(false);
+ const [isEditMemberModalVisible, setIsEditMemberModalVisible] =
+ useState(false);
const [userModels, setUserModels] = useState<string[]>([]);
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [teamToDelete, setTeamToDelete] = useState<string | null>(null);
const [modelsToPick, setModelsToPick] = useState<string[]>([]);
- const [perTeamInfo, setPerTeamInfo] = useState<Record<string, PerTeamInfo>>({});
+ const [perTeamInfo, setPerTeamInfo] = useState<Record<string, PerTeamInfo>>(
+ {}
+ );
// Add this state near the other useState declarations
const [guardrailsList, setGuardrailsList] = useState<string[]>([]);
- const [expandedAccordions, setExpandedAccordions] = useState<Record<string, boolean>>({});
+ const [expandedAccordions, setExpandedAccordions] = useState<
+ Record<string, boolean>
+ >({});
const [loggingSettings, setLoggingSettings] = useState<any[]>([]);
const [mcpAccessGroups, setMcpAccessGroups] = useState<string[]>([]);
const [mcpAccessGroupsLoaded, setMcpAccessGroupsLoaded] = useState(false);
@@ -192,7 +210,7 @@ const Teams: React.FC<TeamProps> = ({
const models = getOrganizationModels(currentOrgForCreateTeam, userModels);
console.log(`models: ${models}`);
setModelsToPick(models);
- form.setFieldValue('models', []);
+ form.setFieldValue("models", []);
}, [currentOrgForCreateTeam, userModels]);
// Add this useEffect to fetch guardrails
@@ -235,17 +253,20 @@ const Teams: React.FC<TeamProps> = ({
useEffect(() => {
const fetchTeamInfo = () => {
if (!teams) return;
-
- const newPerTeamInfo = teams.reduce((acc, team) => {
- acc[team.team_id] = {
- keys: team.keys || [],
- team_info: {
- members_with_roles: team.members_with_roles || []
- }
- };
- return acc;
- }, {} as Record<string, PerTeamInfo>);
-
+
+ const newPerTeamInfo = teams.reduce(
+ (acc, team) => {
+ acc[team.team_id] = {
+ keys: team.keys || [],
+ team_info: {
+ members_with_roles: team.members_with_roles || [],
+ },
+ };
+ return acc;
+ },
+ {} as Record<string, PerTeamInfo>
+ );
+
setPerTeamInfo(newPerTeamInfo);
};
@@ -290,7 +311,7 @@ const Teams: React.FC<TeamProps> = ({
try {
await teamDeleteCall(accessToken, teamToDelete);
// Successfully completed the deletion. Update the state to trigger a rerender.
- fetchTeams(accessToken, userID, userRole, currentOrg, setTeams)
+ fetchTeams(accessToken, userID, userRole, currentOrg, setTeams);
} catch (error) {
console.error("Error deleting the team:", error);
// Handle any error situations, such as displaying an error message to the user.
@@ -313,7 +334,11 @@ const Teams: React.FC<TeamProps> = ({
if (userID === null || userRole === null || accessToken === null) {
return;
}
- const models = await fetchAvailableModelsForTeamOrKey(userID, userRole, accessToken);
+ const models = await fetchAvailableModelsForTeamOrKey(
+ userID,
+ userRole,
+ accessToken
+ );
if (models) {
setUserModels(models);
}
@@ -331,14 +356,14 @@ const Teams: React.FC<TeamProps> = ({
if (accessToken != null) {
const newTeamAlias = formValues?.team_alias;
const existingTeamAliases = teams?.map((t) => t.team_alias) ?? [];
- let organizationId = formValues?.organization_id || currentOrg?.organization_id;
- if (organizationId === "" || typeof organizationId !== 'string') {
+ let organizationId =
+ formValues?.organization_id || currentOrg?.organization_id;
+ if (organizationId === "" || typeof organizationId !== "string") {
formValues.organization_id = null;
} else {
formValues.organization_id = organizationId.trim();
}
-
// Remove guardrails from top level since it's now in metadata
if (existingTeamAliases.includes(newTeamAlias)) {
throw new Error(
@@ -347,7 +372,7 @@ const Teams: React.FC<TeamProps> = ({
}
message.info("Creating Team");
-
+
// Handle logging settings in metadata
if (loggingSettings.length > 0) {
let metadata = {};
@@ -355,31 +380,42 @@ const Teams: React.FC<TeamProps> = ({
try {
metadata = JSON.parse(formValues.metadata);
} catch (e) {
- console.warn("Invalid JSON in metadata field, starting with empty object");
+ console.warn(
+ "Invalid JSON in metadata field, starting with empty object"
+ );
}
}
-
+
// Add logging settings to metadata
metadata = {
...metadata,
- logging: loggingSettings.filter(config => config.callback_name) // Only include configs with callback_name
+ logging: loggingSettings.filter((config) => config.callback_name), // Only include configs with callback_name
};
-
+
formValues.metadata = JSON.stringify(metadata);
}
-
+
// Transform allowed_vector_store_ids and allowed_mcp_servers_and_groups into object_permission
if (
- (formValues.allowed_vector_store_ids && formValues.allowed_vector_store_ids.length > 0) ||
- (formValues.allowed_mcp_servers_and_groups && (formValues.allowed_mcp_servers_and_groups.servers?.length > 0 || formValues.allowed_mcp_servers_and_groups.accessGroups?.length > 0))
+ (formValues.allowed_vector_store_ids &&
+ formValues.allowed_vector_store_ids.length > 0) ||
+ (formValues.allowed_mcp_servers_and_groups &&
+ (formValues.allowed_mcp_servers_and_groups.servers?.length > 0 ||
+ formValues.allowed_mcp_servers_and_groups.accessGroups?.length >
+ 0))
) {
formValues.object_permission = {};
- if (formValues.allowed_vector_store_ids && formValues.allowed_vector_store_ids.length > 0) {
- formValues.object_permission.vector_stores = formValues.allowed_vector_store_ids;
+ if (
+ formValues.allowed_vector_store_ids &&
+ formValues.allowed_vector_store_ids.length > 0
+ ) {
+ formValues.object_permission.vector_stores =
+ formValues.allowed_vector_store_ids;
delete formValues.allowed_vector_store_ids;
}
if (formValues.allowed_mcp_servers_and_groups) {
- const { servers, accessGroups } = formValues.allowed_mcp_servers_and_groups;
+ const { servers, accessGroups } =
+ formValues.allowed_mcp_servers_and_groups;
if (servers && servers.length > 0) {
formValues.object_permission.mcp_servers = servers;
}
@@ -391,11 +427,15 @@ const Teams: React.FC<TeamProps> = ({
}
// Transform allowed_mcp_access_groups into object_permission
- if (formValues.allowed_mcp_access_groups && formValues.allowed_mcp_access_groups.length > 0) {
+ if (
+ formValues.allowed_mcp_access_groups &&
+ formValues.allowed_mcp_access_groups.length > 0
+ ) {
if (!formValues.object_permission) {
formValues.object_permission = {};
}
- formValues.object_permission.mcp_access_groups = formValues.allowed_mcp_access_groups;
+ formValues.object_permission.mcp_access_groups =
+ formValues.allowed_mcp_access_groups;
delete formValues.allowed_mcp_access_groups;
}
const response: any = await teamCreateCall(accessToken, formValues);
@@ -427,9 +467,7 @@ const Teams: React.FC<TeamProps> = ({
}
}
return false;
- }
-
-
+ };
const handleRefreshClick = () => {
// Update the 'lastRefreshed' state to the current date and time
@@ -448,21 +486,23 @@ const Teams: React.FC<TeamProps> = ({
null,
newFilters.team_id || null,
newFilters.team_alias || null
- ).then((response) => {
- if (response && response.teams) {
- setTeams(response.teams);
- }
- }).catch((error) => {
- console.error("Error fetching teams:", error);
- });
+ )
+ .then((response) => {
+ if (response && response.teams) {
+ setTeams(response.teams);
+ }
+ })
+ .catch((error) => {
+ console.error("Error fetching teams:", error);
+ });
}
};
- const handleSortChange = (sortBy: string, sortOrder: 'asc' | 'desc') => {
+ const handleSortChange = (sortBy: string, sortOrder: "asc" | "desc") => {
const newFilters = {
...filters,
sort_by: sortBy,
- sort_order: sortOrder
+ sort_order: sortOrder,
};
setFilters(newFilters);
// Call teamListCall with the new sort parameters
@@ -473,13 +513,15 @@ const Teams: React.FC<TeamProps> = ({
null,
filters.team_id || null,
filters.team_alias || null
- ).then((response) => {
- if (response && response.teams) {
- setTeams(response.teams);
- }
- }).catch((error) => {
- console.error("Error fetching teams:", error);
- });
+ )
+ .then((response) => {
+ if (response && response.teams) {
+ setTeams(response.teams);
+ }
+ })
+ .catch((error) => {
+ console.error("Error fetching teams:", error);
+ });
}
};
@@ -489,17 +531,19 @@ const Teams: React.FC<TeamProps> = ({
team_alias: "",
organization_id: "",
sort_by: "created_at",
- sort_order: "desc"
+ sort_order: "desc",
});
// Reset teams list
if (accessToken) {
- v2TeamListCall(accessToken, null, userID || null, null, null).then((response) => {
- if (response && response.teams) {
- setTeams(response.teams);
- }
- }).catch((error) => {
- console.error("Error fetching teams:", error);
- });
+ v2TeamListCall(accessToken, null, userID || null, null, null)
+ .then((response) => {
+ if (response && response.teams) {
+ setTeams(response.teams);
+ }
+ })
+ .catch((error) => {
+ console.error("Error fetching teams:", error);
+ });
}
};
@@ -507,54 +551,58 @@ const Teams: React.FC<TeamProps> = ({
<div className="w-full mx-4 h-[75vh]">
<Grid numItems={1} className="gap-2 p-8 w-full mt-2">
<Col numColSpan={1} className="flex flex-col gap-2">
- {
- (userRole == "Admin" || userRole == "Org Admin") && !selectedTeamId?
- <Button
- className="w-fit"
- onClick={() => setIsTeamModalVisible(true)}
- >
- + Create New Team
- </Button> : null
- }
+ {(userRole == "Admin" || userRole == "Org Admin") && (
+ <Button
+ className="w-fit"
+ onClick={() => setIsTeamModalVisible(true)}
+ >
+ + Create New Team
+ </Button>
+ )}
{selectedTeamId ? (
- <TeamInfoView
- teamId={selectedTeamId}
- onUpdate={(data) => {
- setTeams(teams => {
+ <TeamInfoView
+ teamId={selectedTeamId}
+ onUpdate={(data) => {
+ setTeams((teams) => {
if (teams == null) {
return teams;
}
-
- return teams.map(team => {
+
+ return teams.map((team) => {
if (data.team_id === team.team_id) {
- return updateExistingKeys(team, data)
+ return updateExistingKeys(team, data);
}
-
- return team
- })
- })
-
- }}
- onClose={() => {
- setSelectedTeamId(null);
- setEditTeam(false);
- }}
- accessToken={accessToken}
- is_team_admin={is_team_admin(teams?.find((team) => team.team_id === selectedTeamId))}
- is_proxy_admin={userRole == "Admin"}
- userModels={userModels}
- editTeam={editTeam}
- />
+
+ return team;
+ });
+ });
+ }}
+ onClose={() => {
+ setSelectedTeamId(null);
+ setEditTeam(false);
+ }}
+ accessToken={accessToken}
+ is_team_admin={is_team_admin(
+ teams?.find((team) => team.team_id === selectedTeamId)
+ )}
+ is_proxy_admin={userRole == "Admin"}
+ userModels={userModels}
+ editTeam={editTeam}
+ />
) : (
<TabGroup className="gap-2 h-[75vh] w-full">
- <TabList className="flex justify-between mt-2 w-full items-center">
- <div className="flex">
- <Tab>Your Teams</Tab>
- <Tab>Available Teams</Tab>
- {isAdminRole(userRole || "") && <Tab>Default Team Settings</Tab>}
+ <TabList className="flex justify-between mt-2 w-full items-center">
+ <div className="flex">
+ <Tab>Your Teams</Tab>
+ <Tab>Available Teams</Tab>
+ {isAdminRole(userRole || "") && (
+ <Tab>Default Team Settings</Tab>
+ )}
</div>
<div className="flex items-center space-x-2">
- {lastRefreshed && <Text>Last Refreshed: {lastRefreshed}</Text>}
+ {lastRefreshed && (
+ <Text>Last Refreshed: {lastRefreshed}</Text>
+ )}
<Icon
icon={RefreshIcon} // Modify as necessary for correct icon name
variant="shadow"
@@ -563,689 +611,863 @@ const Teams: React.FC<TeamProps> = ({
onClick={handleRefreshClick}
/>
</div>
- </TabList>
- <TabPanels>
- <TabPanel>
- <Text>
- Click on &ldquo;Team ID&rdquo; to view team details <b>and</b> manage team members.
- </Text>
- <Grid numItems={1} className="gap-2 pt-2 pb-2 h-[75vh] w-full mt-2">
- <Col numColSpan={1}>
- <Card className="w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]">
- <div className="border-b px-6 py-4">
- <div className="flex flex-col space-y-4">
- {/* Search and Filter Controls */}
- <div className="flex flex-wrap items-center gap-3">
- {/* Team Alias Search */}
- <div className="relative w-64">
- <input
- type="text"
- placeholder="Search by Team Name..."
- className="w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
- value={filters.team_alias}
- onChange={(e) => handleFilterChange('team_alias', e.target.value)}
- />
- <svg
- className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
- />
- </svg>
- </div>
+ </TabList>
+ <TabPanels>
+ <TabPanel>
+ <Text>
+ Click on &ldquo;Team ID&rdquo; to view team details{" "}
+ <b>and</b> manage team members.
+ </Text>
+ <Grid
+ numItems={1}
+ className="gap-2 pt-2 pb-2 h-[75vh] w-full mt-2"
+ >
+ <Col numColSpan={1}>
+ <Card className="w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]">
+ <div className="border-b px-6 py-4">
+ <div className="flex flex-col space-y-4">
+ {/* Search and Filter Controls */}
+ <div className="flex flex-wrap items-center gap-3">
+ {/* Team Alias Search */}
+ <div className="relative w-64">
+ <input
+ type="text"
+ placeholder="Search by Team Name..."
+ className="w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
+ value={filters.team_alias}
+ onChange={(e) =>
+ handleFilterChange(
+ "team_alias",
+ e.target.value
+ )
+ }
+ />
+ <svg
+ className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
+ />
+ </svg>
+ </div>
- {/* Filter Button */}
- <button
- className={`px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ${showFilters ? 'bg-gray-100' : ''}`}
- onClick={() => setShowFilters(!showFilters)}
- >
- <svg
- className="w-4 h-4"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"
- />
- </svg>
- Filters
- {(filters.team_id || filters.team_alias || filters.organization_id) && (
- <span className="w-2 h-2 rounded-full bg-blue-500"></span>
- )}
- </button>
+ {/* Filter Button */}
+ <button
+ className={`px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ${showFilters ? "bg-gray-100" : ""}`}
+ onClick={() => setShowFilters(!showFilters)}
+ >
+ <svg
+ className="w-4 h-4"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"
+ />
+ </svg>
+ Filters
+ {(filters.team_id ||
+ filters.team_alias ||
+ filters.organization_id) && (
+ <span className="w-2 h-2 rounded-full bg-blue-500"></span>
+ )}
+ </button>
- {/* Reset Filters Button */}
- <button
- className="px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2"
- onClick={handleFilterReset}
- >
- <svg
- className="w-4 h-4"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
- />
- </svg>
- Reset Filters
- </button>
- </div>
+ {/* Reset Filters Button */}
+ <button
+ className="px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2"
+ onClick={handleFilterReset}
+ >
+ <svg
+ className="w-4 h-4"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
+ />
+ </svg>
+ Reset Filters
+ </button>
+ </div>
- {/* Additional Filters */}
- {showFilters && (
- <div className="flex flex-wrap items-center gap-3 mt-3">
- {/* Team ID Search */}
- <div className="relative w-64">
- <input
- type="text"
- placeholder="Enter Team ID"
- className="w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
- value={filters.team_id}
- onChange={(e) => handleFilterChange('team_id', e.target.value)}
- />
- <svg
- className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"
- />
- </svg>
- </div>
+ {/* Additional Filters */}
+ {showFilters && (
+ <div className="flex flex-wrap items-center gap-3 mt-3">
+ {/* Team ID Search */}
+ <div className="relative w-64">
+ <input
+ type="text"
+ placeholder="Enter Team ID"
+ className="w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
+ value={filters.team_id}
+ onChange={(e) =>
+ handleFilterChange(
+ "team_id",
+ e.target.value
+ )
+ }
+ />
+ <svg
+ className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500"
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"
+ />
+ </svg>
+ </div>
- {/* Organization Dropdown */}
- <div className="w-64">
- <Select
- value={filters.organization_id || ""}
- onValueChange={(value) => handleFilterChange('organization_id', value)}
- placeholder="Select Organization"
- >
- {organizations?.map((org) => (
- <SelectItem key={org.organization_id} value={org.organization_id || ""}>
- {org.organization_alias || org.organization_id}
- </SelectItem>
- ))}
- </Select>
+ {/* Organization Dropdown */}
+ <div className="w-64">
+ <Select
+ value={filters.organization_id || ""}
+ onValueChange={(value) =>
+ handleFilterChange(
+ "organization_id",
+ value
+ )
+ }
+ placeholder="Select Organization"
+ >
+ {organizations?.map((org) => (
+ <SelectItem
+ key={org.organization_id}
+ value={org.organization_id || ""}
+ >
+ {org.organization_alias ||
+ org.organization_id}
+ </SelectItem>
+ ))}
+ </Select>
+ </div>
+ </div>
+ )}
</div>
</div>
- )}
- </div>
- </div>
- <Table>
- <TableHead>
- <TableRow>
- <TableHeaderCell>Team Name</TableHeaderCell>
- <TableHeaderCell>Team ID</TableHeaderCell>
- <TableHeaderCell>Created</TableHeaderCell>
- <TableHeaderCell>Spend (USD)</TableHeaderCell>
- <TableHeaderCell>Budget (USD)</TableHeaderCell>
- <TableHeaderCell>Models</TableHeaderCell>
- <TableHeaderCell>Organization</TableHeaderCell>
- <TableHeaderCell>Info</TableHeaderCell>
- </TableRow>
- </TableHead>
-
- <TableBody>
- {teams && teams.length > 0
- ? teams
- .filter((team) => {
- if (!currentOrg) return true;
- return team.organization_id === currentOrg.organization_id;
- })
- .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
- .map((team: any) => (
- <TableRow key={team.team_id}>
- <TableCell
- style={{
- maxWidth: "4px",
- whiteSpace: "pre-wrap",
- overflow: "hidden",
- }}
- >
- {team["team_alias"]}
- </TableCell>
- <TableCell>
- <div className="overflow-hidden">
- <Tooltip title={team.team_id}>
- <Button
- size="xs"
- variant="light"
- className="font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]"
-
- onClick={() => {
- // Add click handler
- setSelectedTeamId(team.team_id);
- }}
- >
- {team.team_id.slice(0, 7)}...
- </Button>
- </Tooltip>
- </div>
- </TableCell>
- <TableCell
- style={{
- maxWidth: "4px",
- whiteSpace: "pre-wrap",
- overflow: "hidden",
- }}
- >
- {team.created_at ? new Date(team.created_at).toLocaleDateString() : "N/A"}
- </TableCell>
- <TableCell
- style={{
- maxWidth: "4px",
- whiteSpace: "pre-wrap",
- overflow: "hidden",
- }}
- >
- {formatNumberWithCommas(team["spend"], 4)}
- </TableCell>
- <TableCell
- style={{
- maxWidth: "4px",
- whiteSpace: "pre-wrap",
- overflow: "hidden",
- }}
- >
- {team["max_budget"] !== null && team["max_budget"] !== undefined ? team["max_budget"] : "No limit"}
- </TableCell>
- <TableCell
- style={{
- maxWidth: "8-x",
- whiteSpace: "pre-wrap",
- overflow: "hidden",
- }}
- className={team.models.length > 3 ? "px-0" : ""}
- >
- <div className="flex flex-col">
- {Array.isArray(team.models) ? (
- <div className="flex flex-col">
- {team.models.length === 0 ? (
- <Badge size={"xs"} className="mb-1" color="red">
- <Text>All Proxy Models</Text>
- </Badge>
- ) : (
- <>
- <div className="flex items-start">
- {team.models.length > 3 && (
- <div>
- <Icon
- icon={expandedAccordions[team.team_id] ? ChevronDownIcon : ChevronRightIcon}
- className="cursor-pointer"
- size="xs"
- onClick={() => {
- setExpandedAccordions(prev => ({
- ...prev,
- [team.team_id]: !prev[team.team_id]
- }));
- }}
- />
- </div>
- )}
- <div className="flex flex-wrap gap-1">
- {team.models.slice(0, 3).map((model: string, index: number) => (
- model === "all-proxy-models" ? (
- <Badge
- key={index}
- size={"xs"}
- color="red"
- >
- <Text>All Proxy Models</Text>
- </Badge>
- ) : (
- <Badge
- key={index}
- size={"xs"}
- color="blue"
+ <Table>
+ <TableHead>
+ <TableRow>
+ <TableHeaderCell>Team Name</TableHeaderCell>
+ <TableHeaderCell>Team ID</TableHeaderCell>
+ <TableHeaderCell>Created</TableHeaderCell>
+ <TableHeaderCell>Spend (USD)</TableHeaderCell>
+ <TableHeaderCell>Budget (USD)</TableHeaderCell>
+ <TableHeaderCell>Models</TableHeaderCell>
+ <TableHeaderCell>Organization</TableHeaderCell>
+ <TableHeaderCell>Info</TableHeaderCell>
+ </TableRow>
+ </TableHead>
+
+ <TableBody>
+ {teams && teams.length > 0
+ ? teams
+ .filter((team) => {
+ if (!currentOrg) return true;
+ return (
+ team.organization_id ===
+ currentOrg.organization_id
+ );
+ })
+ .sort(
+ (a, b) =>
+ new Date(b.created_at).getTime() -
+ new Date(a.created_at).getTime()
+ )
+ .map((team: any) => (
+ <TableRow key={team.team_id}>
+ <TableCell
+ style={{
+ maxWidth: "4px",
+ whiteSpace: "pre-wrap",
+ overflow: "hidden",
+ }}
+ >
+ {team["team_alias"]}
+ </TableCell>
+ <TableCell>
+ <div className="overflow-hidden">
+ <Tooltip title={team.team_id}>
+ <Button
+ size="xs"
+ variant="light"
+ className="font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]"
+ onClick={() => {
+ // Add click handler
+ setSelectedTeamId(team.team_id);
+ }}
>
- <Text>
- {model.length > 30
- ? `${getModelDisplayName(model).slice(0, 30)}...`
- : getModelDisplayName(model)}
- </Text>
- </Badge>
- )
- ))}
- {team.models.length > 3 && !expandedAccordions[team.team_id] && (
- <Badge size={"xs"} color="gray" className="cursor-pointer">
- <Text>+{team.models.length - 3} {team.models.length - 3 === 1 ? 'more model' : 'more models'}</Text>
- </Badge>
+ {team.team_id.slice(0, 7)}...
+ </Button>
+ </Tooltip>
+ </div>
+ </TableCell>
+ <TableCell
+ style={{
+ maxWidth: "4px",
+ whiteSpace: "pre-wrap",
+ overflow: "hidden",
+ }}
+ >
+ {team.created_at
+ ? new Date(
+ team.created_at
+ ).toLocaleDateString()
+ : "N/A"}
+ </TableCell>
+ <TableCell
+ style={{
+ maxWidth: "4px",
+ whiteSpace: "pre-wrap",
+ overflow: "hidden",
+ }}
+ >
+ {formatNumberWithCommas(
+ team["spend"],
+ 4
)}
- {expandedAccordions[team.team_id] && (
- <div className="flex flex-wrap gap-1">
- {team.models.slice(3).map((model: string, index: number) => (
- model === "all-proxy-models" ? (
- <Badge
- key={index + 3}
- size={"xs"}
- color="red"
- >
- <Text>All Proxy Models</Text>
- </Badge>
- ) : (
- <Badge
- key={index + 3}
- size={"xs"}
- color="blue"
- >
- <Text>
- {model.length > 30
- ? `${getModelDisplayName(model).slice(0, 30)}...`
- : getModelDisplayName(model)}
- </Text>
- </Badge>
- )
- ))}
- </div>
- )}
- </div>
- </div>
-
- </>
- )}
+ </TableCell>
+ <TableCell
+ style={{
+ maxWidth: "4px",
+ whiteSpace: "pre-wrap",
+ overflow: "hidden",
+ }}
+ >
+ {team["max_budget"] !== null &&
+ team["max_budget"] !== undefined
+ ? team["max_budget"]
+ : "No limit"}
+ </TableCell>
+ <TableCell
+ style={{
+ maxWidth: "8-x",
+ whiteSpace: "pre-wrap",
+ overflow: "hidden",
+ }}
+ className={
+ team.models.length > 3 ? "px-0" : ""
+ }
+ >
+ <div className="flex flex-col">
+ {Array.isArray(team.models) ? (
+ <div className="flex flex-col">
+ {team.models.length === 0 ? (
+ <Badge
+ size={"xs"}
+ className="mb-1"
+ color="red"
+ >
+ <Text>All Proxy Models</Text>
+ </Badge>
+ ) : (
+ <>
+ <div className="flex items-start">
+ {team.models.length > 3 && (
+ <div>
+ <Icon
+ icon={
+ expandedAccordions[
+ team.team_id
+ ]
+ ? ChevronDownIcon
+ : ChevronRightIcon
+ }
+ className="cursor-pointer"
+ size="xs"
+ onClick={() => {
+ setExpandedAccordions(
+ (prev) => ({
+ ...prev,
+ [team.team_id]:
+ !prev[
+ team.team_id
+ ],
+ })
+ );
+ }}
+ />
+ </div>
+ )}
+ <div className="flex flex-wrap gap-1">
+ {team.models
+ .slice(0, 3)
+ .map(
+ (
+ model: string,
+ index: number
+ ) =>
+ model ===
+ "all-proxy-models" ? (
+ <Badge
+ key={index}
+ size={"xs"}
+ color="red"
+ >
+ <Text>
+ All Proxy
+ Models
+ </Text>
+ </Badge>
+ ) : (
+ <Badge
+ key={index}
+ size={"xs"}
+ color="blue"
+ >
+ <Text>
+ {model.length >
+ 30
+ ? `${getModelDisplayName(model).slice(0, 30)}...`
+ : getModelDisplayName(
+ model
+ )}
+ </Text>
+ </Badge>
+ )
+ )}
+ {team.models.length > 3 &&
+ !expandedAccordions[
+ team.team_id
+ ] && (
+ <Badge
+ size={"xs"}
+ color="gray"
+ className="cursor-pointer"
+ >
+ <Text>
+ +
+ {team.models
+ .length -
+ 3}{" "}
+ {team.models
+ .length -
+ 3 ===
+ 1
+ ? "more model"
+ : "more models"}
+ </Text>
+ </Badge>
+ )}
+ {expandedAccordions[
+ team.team_id
+ ] && (
+ <div className="flex flex-wrap gap-1">
+ {team.models
+ .slice(3)
+ .map(
+ (
+ model: string,
+ index: number
+ ) =>
+ model ===
+ "all-proxy-models" ? (
+ <Badge
+ key={
+ index + 3
+ }
+ size={"xs"}
+ color="red"
+ >
+ <Text>
+ All Proxy
+ Models
+ </Text>
+ </Badge>
+ ) : (
+ <Badge
+ key={
+ index + 3
+ }
+ size={"xs"}
+ color="blue"
+ >
+ <Text>
+ {model.length >
+ 30
+ ? `${getModelDisplayName(model).slice(0, 30)}...`
+ : getModelDisplayName(
+ model
+ )}
+ </Text>
+ </Badge>
+ )
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ ) : null}
+ </div>
+ </TableCell>
+
+ <TableCell>
+ {team.organization_id}
+ </TableCell>
+ <TableCell>
+ <Text>
+ {perTeamInfo &&
+ team.team_id &&
+ perTeamInfo[team.team_id] &&
+ perTeamInfo[team.team_id].keys &&
+ perTeamInfo[team.team_id].keys
+ .length}{" "}
+ Keys
+ </Text>
+ <Text>
+ {perTeamInfo &&
+ team.team_id &&
+ perTeamInfo[team.team_id] &&
+ perTeamInfo[team.team_id]
+ .team_info &&
+ perTeamInfo[team.team_id].team_info
+ .members_with_roles &&
+ perTeamInfo[team.team_id].team_info
+ .members_with_roles.length}{" "}
+ Members
+ </Text>
+ </TableCell>
+ <TableCell>
+ {userRole == "Admin" ? (
+ <>
+ <Icon
+ icon={PencilAltIcon}
+ size="sm"
+ onClick={() => {
+ setSelectedTeamId(team.team_id);
+ setEditTeam(true);
+ }}
+ />
+ <Icon
+ onClick={() =>
+ handleDelete(team.team_id)
+ }
+ icon={TrashIcon}
+ size="sm"
+ />
+ </>
+ ) : null}
+ </TableCell>
+ </TableRow>
+ ))
+ : null}
+ </TableBody>
+ </Table>
+ {isDeleteModalOpen && (
+ <div className="fixed z-10 inset-0 overflow-y-auto">
+ <div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
+ <div
+ className="fixed inset-0 transition-opacity"
+ aria-hidden="true"
+ >
+ <div className="absolute inset-0 bg-gray-500 opacity-75"></div>
</div>
- ) : null}
- </div>
- </TableCell>
-
- <TableCell>
- {team.organization_id}
- </TableCell>
- <TableCell>
- <Text>
- {perTeamInfo &&
- team.team_id &&
- perTeamInfo[team.team_id] &&
- perTeamInfo[team.team_id].keys &&
- perTeamInfo[team.team_id].keys.length}{" "}
- Keys
- </Text>
- <Text>
- {perTeamInfo &&
- team.team_id &&
- perTeamInfo[team.team_id] &&
- perTeamInfo[team.team_id].team_info &&
- perTeamInfo[team.team_id].team_info.members_with_roles &&
- perTeamInfo[team.team_id].team_info.members_with_roles.length}{" "}
- Members
- </Text>
- </TableCell>
- <TableCell>
- {userRole == "Admin" ? (
- <>
- <Icon
- icon={PencilAltIcon}
- size="sm"
- onClick={() => {
- setSelectedTeamId(team.team_id);
- setEditTeam(true);
- }}
- />
- <Icon
- onClick={() => handleDelete(team.team_id)}
- icon={TrashIcon}
- size="sm"
- />
- </>
- ) : null}
- </TableCell>
- </TableRow>
- ))
- : null}
- </TableBody>
- </Table>
- {isDeleteModalOpen && (
- <div className="fixed z-10 inset-0 overflow-y-auto">
- <div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
- <div
- className="fixed inset-0 transition-opacity"
- aria-hidden="true"
- >
- <div className="absolute inset-0 bg-gray-500 opacity-75"></div>
- </div>
- {/* Modal Panel */}
- <span
- className="hidden sm:inline-block sm:align-middle sm:h-screen"
- aria-hidden="true"
- >
- &#8203;
- </span>
-
- {/* Confirmation Modal Content */}
- <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
- <div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
- <div className="sm:flex sm:items-start">
- <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
- <h3 className="text-lg leading-6 font-medium text-gray-900">
- Delete Team
- </h3>
- <div className="mt-2">
- <p className="text-sm text-gray-500">
- Are you sure you want to delete this team ?
- </p>
+ {/* Modal Panel */}
+ <span
+ className="hidden sm:inline-block sm:align-middle sm:h-screen"
+ aria-hidden="true"
+ >
+ &#8203;
+ </span>
+
+ {/* Confirmation Modal Content */}
+ <div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
+ <div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
+ <div className="sm:flex sm:items-start">
+ <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
+ <h3 className="text-lg leading-6 font-medium text-gray-900">
+ Delete Team
+ </h3>
+ <div className="mt-2">
+ <p className="text-sm text-gray-500">
+ Are you sure you want to delete this
+ team ?
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
+ <Button
+ onClick={confirmDelete}
+ color="red"
+ className="ml-2"
+ >
+ Delete
+ </Button>
+ <Button onClick={cancelDelete}>Cancel</Button>
</div>
</div>
</div>
</div>
- <div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
- <Button
- onClick={confirmDelete}
- color="red"
- className="ml-2"
- >
- Delete
- </Button>
- <Button onClick={cancelDelete}>Cancel</Button>
- </div>
- </div>
- </div>
- </div>
- )}
- </Card>
- </Col>
- {userRole == "Admin" || userRole == "Org Admin"? (
- <Col numColSpan={1}>
- <Modal
- title="Create Team"
- visible={isTeamModalVisible}
- width={1000}
- footer={null}
- onOk={handleOk}
- onCancel={handleCancel}
- >
- <Form
- form={form}
- onFinish={handleCreate}
- labelCol={{ span: 8 }}
- wrapperCol={{ span: 16 }}
- labelAlign="left"
+ )}
+ </Card>
+ </Col>
+ </Grid>
+ </TabPanel>
+ <TabPanel>
+ <AvailableTeamsPanel
+ accessToken={accessToken}
+ userID={userID}
+ />
+ </TabPanel>
+ {isAdminRole(userRole || "") && (
+ <TabPanel>
+ <TeamSSOSettings
+ accessToken={accessToken}
+ userID={userID || ""}
+ userRole={userRole || ""}
+ />
+ </TabPanel>
+ )}
+ </TabPanels>
+ </TabGroup>
+ )}
+ {(userRole == "Admin" || userRole == "Org Admin") && (
+ <Modal
+ title="Create Team"
+ visible={isTeamModalVisible}
+ width={1000}
+ footer={null}
+ onOk={handleOk}
+ onCancel={handleCancel}
+ >
+ <Form
+ form={form}
+ onFinish={handleCreate}
+ labelCol={{ span: 8 }}
+ wrapperCol={{ span: 16 }}
+ labelAlign="left"
+ >
+ <>
+ <Form.Item
+ label="Team Name"
+ name="team_alias"
+ rules={[
+ {
+ required: true,
+ message: "Please input a team name",
+ },
+ ]}
+ >
+ <TextInput placeholder="" />
+ </Form.Item>
+ <Form.Item
+ label={
+ <span>
+ Organization{" "}
+ <Tooltip
+ title={
+ <span>
+ Organizations can have multiple teams. Learn more
+ about{" "}
+ <a
+ href="https://docs.litellm.ai/docs/proxy/user_management_heirarchy"
+ target="_blank"
+ rel="noopener noreferrer"
+ style={{
+ color: "#1890ff",
+ textDecoration: "underline",
+ }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ user management hierarchy
+ </a>
+ </span>
+ }
+ >
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="organization_id"
+ initialValue={
+ currentOrg ? currentOrg.organization_id : null
+ }
+ className="mt-8"
+ >
+ <Select2
+ showSearch
+ allowClear
+ placeholder="Search or select an Organization"
+ onChange={(value) => {
+ form.setFieldValue("organization_id", value);
+ setCurrentOrgForCreateTeam(
+ organizations?.find(
+ (org) => org.organization_id === value
+ ) || null
+ );
+ }}
+ filterOption={(input, option) => {
+ if (!option) return false;
+ const optionValue = option.children?.toString() || "";
+ return optionValue
+ .toLowerCase()
+ .includes(input.toLowerCase());
+ }}
+ optionFilterProp="children"
+ >
+ {organizations?.map((org) => (
+ <Select2.Option
+ key={org.organization_id}
+ value={org.organization_id}
+ >
+ <span className="font-medium">
+ {org.organization_alias}
+ </span>{" "}
+ <span className="text-gray-500">
+ ({org.organization_id})
+ </span>
+ </Select2.Option>
+ ))}
+ </Select2>
+ </Form.Item>
+ <Form.Item
+ label={
+ <span>
+ Models{" "}
+ <Tooltip title="These are the models that your selected team has access to">
+ <InfoCircleOutlined style={{ marginLeft: "4px" }} />
+ </Tooltip>
+ </span>
+ }
+ name="models"
+ >
+ <Select2
+ mode="multiple"
+ placeholder="Select models"
+ style={{ width: "100%" }}
+ >
+ <Select2.Option
+ key="all-proxy-models"
+ value="all-proxy-models"
+ >
+ All Proxy Models
+ </Select2.Option>
+ {modelsToPick.map((model) => (
+ <Select2.Option key={model} value={model}>
+ {getModelDisplayName(model)}
+ </Select2.Option>
+ ))}
+ </Select2>
+ </Form.Item>
+
+ <Form.Item label="Max Budget (USD)" name="max_budget">
+ <NumericalInput step={0.01} precision={2} width={200} />
+ </Form.Item>
+ <Form.Item
+ className="mt-8"
+ label="Reset Budget"
+ name="budget_duration"
+ >
+ <Select2 defaultValue={null} placeholder="n/a">
+ <Select2.Option value="24h">daily</Select2.Option>
+ <Select2.Option value="7d">weekly</Select2.Option>
+ <Select2.Option value="30d">monthly</Select2.Option>
+ </Select2>
+ </Form.Item>
+ <Form.Item
+ label="Tokens per minute Limit (TPM)"
+ name="tpm_limit"
+ >
+ <NumericalInput step={1} width={400} />
+ </Form.Item>
+ <Form.Item
+ label="Requests per minute Limit (RPM)"
+ name="rpm_limit"
>
- <>
+ <NumericalInput step={1} width={400} />
+ </Form.Item>
+
+ <Accordion
+ className="mt-20 mb-8"
+ onClick={() => {
+ if (!mcpAccessGroupsLoaded) {
+ fetchMcpAccessGroups();
+ setMcpAccessGroupsLoaded(true);
+ }
+ }}
+ >
+ <AccordionHeader>
+ <b>Additional Settings</b>
+ </AccordionHeader>
+ <AccordionBody>
+ <Form.Item
+ label="Team ID"
+ name="team_id"
+ help="ID of the team you want to create. If not provided, it will be generated automatically."
+ >
+ <TextInput
+ onChange={(e) => {
+ e.target.value = e.target.value.trim();
+ }}
+ />
+ </Form.Item>
+ <Form.Item
+ label="Team Member Budget (USD)"
+ name="team_member_budget"
+ normalize={(value) =>
+ value ? Number(value) : undefined
+ }
+ tooltip="This is the individual budget for a user in the team."
+ >
+ <NumericalInput step={0.01} precision={2} width={200} />
+ </Form.Item>
+ <Form.Item
+ label="Team Member Key Duration"
+ name="team_member_key_duration"
+ tooltip="Set a limit to the duration of a team member's key."
+ >
+ <Select2 defaultValue={null} placeholder="n/a">
+ <Select2.Option value="1d">1 day</Select2.Option>
+ <Select2.Option value="1w">1 week</Select2.Option>
+ <Select2.Option value="1mo">1 month</Select2.Option>
+ </Select2>
+ </Form.Item>
<Form.Item
- label="Team Name"
- name="team_alias"
- rules={[
- { required: true, message: "Please input a team name" },
- ]}
+ label="Metadata"
+ name="metadata"
+ help="Additional team metadata. Enter metadata as JSON object."
>
- <TextInput placeholder="" />
+ <Input.TextArea rows={4} />
</Form.Item>
<Form.Item
label={
<span>
- Organization{' '}
- <Tooltip title={
- <span>
- Organizations can have multiple teams. Learn more about{' '}
- <a
- href="https://docs.litellm.ai/docs/proxy/user_management_heirarchy"
- target="_blank"
- rel="noopener noreferrer"
- style={{ color: '#1890ff', textDecoration: 'underline' }}
- onClick={(e) => e.stopPropagation()}
- >
- user management hierarchy
- </a>
- </span>
- }>
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
+ Guardrails{" "}
+ <Tooltip title="Setup your first guardrail">
+ <a
+ href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <InfoCircleOutlined
+ style={{ marginLeft: "4px" }}
+ />
+ </a>
</Tooltip>
</span>
}
- name="organization_id"
- initialValue={currentOrg ? currentOrg.organization_id : null}
+ name="guardrails"
className="mt-8"
+ help="Select existing guardrails or enter new ones"
>
<Select2
- showSearch
- allowClear
- placeholder="Search or select an Organization"
- onChange={(value) => {
- form.setFieldValue('organization_id', value);
- setCurrentOrgForCreateTeam(organizations?.find((org) => org.organization_id === value) || null);
- }}
- filterOption={(input, option) => {
- if (!option) return false;
- const optionValue = option.children?.toString() || '';
- return optionValue.toLowerCase().includes(input.toLowerCase());
- }}
- optionFilterProp="children"
- >
- {organizations?.map((org) => (
- <Select2.Option key={org.organization_id} value={org.organization_id}>
- <span className="font-medium">{org.organization_alias}</span>{" "}
- <span className="text-gray-500">({org.organization_id})</span>
- </Select2.Option>
- ))}
- </Select2>
+ mode="tags"
+ style={{ width: "100%" }}
+ placeholder="Select or enter guardrails"
+ options={guardrailsList.map((name) => ({
+ value: name,
+ label: name,
+ }))}
+ />
</Form.Item>
- <Form.Item label={
+ <Form.Item
+ label={
<span>
- Models{' '}
- <Tooltip title="These are the models that your selected team has access to">
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
+ Allowed Vector Stores{" "}
+ <Tooltip title="Select which vector stores this team can access by default. Leave empty for access to all vector stores">
+ <InfoCircleOutlined
+ style={{ marginLeft: "4px" }}
+ />
</Tooltip>
</span>
- } name="models">
- <Select2
- mode="multiple"
- placeholder="Select models"
- style={{ width: "100%" }}
- >
- <Select2.Option
- key="all-proxy-models"
- value="all-proxy-models"
- >
- All Proxy Models
- </Select2.Option>
- {modelsToPick.map((model) => (
- <Select2.Option key={model} value={model}>
- {getModelDisplayName(model)}
- </Select2.Option>
- ))}
- </Select2>
- </Form.Item>
-
- <Form.Item label="Max Budget (USD)" name="max_budget">
- <NumericalInput step={0.01} precision={2} width={200} />
- </Form.Item>
- <Form.Item
+ }
+ name="allowed_vector_store_ids"
className="mt-8"
- label="Reset Budget"
- name="budget_duration"
- >
- <Select2 defaultValue={null} placeholder="n/a">
- <Select2.Option value="24h">daily</Select2.Option>
- <Select2.Option value="7d">weekly</Select2.Option>
- <Select2.Option value="30d">monthly</Select2.Option>
- </Select2>
- </Form.Item>
- <Form.Item
- label="Tokens per minute Limit (TPM)"
- name="tpm_limit"
+ help="Select vector stores this team can access. Leave empty for access to all vector stores"
>
- <NumericalInput step={1} width={400} />
+ <PremiumVectorStoreSelector
+ onChange={(values) =>
+ form.setFieldValue(
+ "allowed_vector_store_ids",
+ values
+ )
+ }
+ value={form.getFieldValue("allowed_vector_store_ids")}
+ accessToken={accessToken || ""}
+ placeholder="Select vector stores (optional)"
+ premiumUser={premiumUser}
+ />
</Form.Item>
<Form.Item
- label="Requests per minute Limit (RPM)"
- name="rpm_limit"
+ label={
+ <span>
+ Allowed MCP Servers{" "}
+ <Tooltip title="Select which MCP servers or access groups this team can access by default. ">
+ <InfoCircleOutlined
+ style={{ marginLeft: "4px" }}
+ />
+ </Tooltip>
+ </span>
+ }
+ name="allowed_mcp_servers_and_groups"
+ className="mt-8"
+ help="Select MCP servers or access groups this team can access. "
>
- <NumericalInput step={1} width={400} />
+ <PremiumMCPSelector
+ onChange={(val) =>
+ form.setFieldValue(
+ "allowed_mcp_servers_and_groups",
+ val
+ )
+ }
+ value={form.getFieldValue(
+ "allowed_mcp_servers_and_groups"
+ )}
+ accessToken={accessToken || ""}
+ placeholder="Select MCP servers or access groups (optional)"
+ premiumUser={premiumUser}
+ />
</Form.Item>
+ </AccordionBody>
+ </Accordion>
- <Accordion className="mt-20 mb-8" onClick={() => { if (!mcpAccessGroupsLoaded) { fetchMcpAccessGroups(); setMcpAccessGroupsLoaded(true); } }}>
- <AccordionHeader>
- <b>Additional Settings</b>
- </AccordionHeader>
- <AccordionBody>
- <Form.Item
- label="Team ID"
- name="team_id"
- help="ID of the team you want to create. If not provided, it will be generated automatically."
- >
- <TextInput
- onChange={(e) => {
- e.target.value = e.target.value.trim();
- }}
- />
- </Form.Item>
- <Form.Item
- label="Team Member Budget (USD)"
- name="team_member_budget"
- normalize={(value) => value ? Number(value) : undefined}
- tooltip="This is the individual budget for a user in the team."
- >
- <NumericalInput step={0.01} precision={2} width={200} />
- </Form.Item>
- <Form.Item
- label="Team Member Key Duration"
- name="team_member_key_duration"
- tooltip="Set a limit to the duration of a team member's key."
- >
- <Select2 defaultValue={null} placeholder="n/a">
- <Select2.Option value="1d">1 day</Select2.Option>
- <Select2.Option value="1w">1 week</Select2.Option>
- <Select2.Option value="1mo">1 month</Select2.Option>
- </Select2>
- </Form.Item>
- <Form.Item label="Metadata" name="metadata" help="Additional team metadata. Enter metadata as JSON object.">
- <Input.TextArea rows={4} />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Guardrails{' '}
- <Tooltip title="Setup your first guardrail">
- <a
- href="https://docs.litellm.ai/docs/proxy/guardrails/quick_start"
- target="_blank"
- rel="noopener noreferrer"
- onClick={(e) => e.stopPropagation()}
- >
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
- </a>
- </Tooltip>
- </span>
- }
- name="guardrails"
- className="mt-8"
- help="Select existing guardrails or enter new ones"
- >
- <Select2
- mode="tags"
- style={{ width: '100%' }}
- placeholder="Select or enter guardrails"
- options={guardrailsList.map(name => ({ value: name, label: name }))}
- />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Allowed Vector Stores{' '}
- <Tooltip title="Select which vector stores this team can access by default. Leave empty for access to all vector stores">
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
- </Tooltip>
- </span>
- }
- name="allowed_vector_store_ids"
- className="mt-8"
- help="Select vector stores this team can access. Leave empty for access to all vector stores"
- >
- <PremiumVectorStoreSelector
- onChange={(values) => form.setFieldValue('allowed_vector_store_ids', values)}
- value={form.getFieldValue('allowed_vector_store_ids')}
- accessToken={accessToken || ''}
- placeholder="Select vector stores (optional)"
- premiumUser={premiumUser}
- />
- </Form.Item>
- <Form.Item
- label={
- <span>
- Allowed MCP Servers{' '}
- <Tooltip title="Select which MCP servers or access groups this team can access by default. ">
- <InfoCircleOutlined style={{ marginLeft: '4px' }} />
- </Tooltip>
- </span>
- }
- name="allowed_mcp_servers_and_groups"
- className="mt-8"
- help="Select MCP servers or access groups this team can access. "
- >
- <PremiumMCPSelector
- onChange={val => form.setFieldValue('allowed_mcp_servers_and_groups', val)}
- value={form.getFieldValue('allowed_mcp_servers_and_groups')}
- accessToken={accessToken || ''}
- placeholder="Select MCP servers or access groups (optional)"
- premiumUser={premiumUser}
- />
- </Form.Item>
- </AccordionBody>
- </Accordion>
-
- <Accordion className="mt-8 mb-8">
- <AccordionHeader>
- <b>Logging Settings</b>
- </AccordionHeader>
- <AccordionBody>
- <div className="mt-4">
- <PremiumLoggingSettings
- value={loggingSettings}
- onChange={setLoggingSettings}
- premiumUser={premiumUser}
- />
- </div>
- </AccordionBody>
- </Accordion>
- </>
- <div style={{ textAlign: "right", marginTop: "10px" }}>
- <Button2 htmlType="submit">Create Team</Button2>
- </div>
- </Form>
- </Modal>
- </Col>
- ) : null}
- </Grid>
- </TabPanel>
- <TabPanel>
- <AvailableTeamsPanel
- accessToken={accessToken}
- userID={userID}
- />
- </TabPanel>
- {isAdminRole(userRole || "") && (
- <TabPanel>
- <TeamSSOSettings
- accessToken={accessToken}
- userID={userID || ""}
- userRole={userRole || ""}
- />
- </TabPanel>
- )}
- </TabPanels>
-
- </TabGroup>)}
+ <Accordion className="mt-8 mb-8">
+ <AccordionHeader>
+ <b>Logging Settings</b>
+ </AccordionHeader>
+ <AccordionBody>
+ <div className="mt-4">
+ <PremiumLoggingSettings
+ value={loggingSettings}
+ onChange={setLoggingSettings}
+ premiumUser={premiumUser}
+ />
+ </div>
+ </AccordionBody>
+ </Accordion>
+ </>
+ <div style={{ textAlign: "right", marginTop: "10px" }}>
+ <Button2 htmlType="submit">Create Team</Button2>
+ </div>
+ </Form>
+ </Modal>
+ )}
</Col>
</Grid>
</div>
diff --git a/ui/litellm-dashboard/src/components/user_dashboard.tsx b/ui/litellm-dashboard/src/components/user_dashboard.tsx
index b32951f5dbc..c8055b813a8 100644
--- a/ui/litellm-dashboard/src/components/user_dashboard.tsx
+++ b/ui/litellm-dashboard/src/components/user_dashboard.tsx
@@ -1,5 +1,5 @@
-"use client";
-import React, { useState, useEffect } from "react";
+"use client"
+import React, { useState, useEffect } from "react"
import {
userInfoCall,
modelAvailableCall,
@@ -9,67 +9,64 @@ import {
organizationListCall,
DEFAULT_ORGANIZATION,
keyInfoCall,
- getProxyBaseUrl
-} from "./networking";
-import { fetchTeams } from "./common_components/fetch_teams";
-import { Grid, Col, Card, Text, Title } from "@tremor/react";
-import CreateKey from "./create_key_button";
-import ViewKeyTable from "./view_key_table";
-import ViewUserSpend from "./view_user_spend";
-import ViewUserTeam from "./view_user_team";
-import DashboardTeam from "./dashboard_default_team";
-import Onboarding from "../app/onboarding/page";
-import { useSearchParams, useRouter } from "next/navigation";
-import { Team } from "./key_team_helpers/key_list";
-import { jwtDecode } from "jwt-decode";
-import { Typography } from "antd";
-import { clearTokenCookies } from "@/utils/cookieUtils";
+ getProxyBaseUrl,
+} from "./networking"
+import { fetchTeams } from "./common_components/fetch_teams"
+import { Grid, Col, Card, Text, Title } from "@tremor/react"
+import CreateKey from "./create_key_button"
+import ViewKeyTable from "./view_key_table"
+import ViewUserSpend from "./view_user_spend"
+import ViewUserTeam from "./view_user_team"
+import DashboardTeam from "./dashboard_default_team"
+import Onboarding from "../app/onboarding/page"
+import { useSearchParams, useRouter } from "next/navigation"
+import { Team } from "./key_team_helpers/key_list"
+import { jwtDecode } from "jwt-decode"
+import { Typography } from "antd"
+import { clearTokenCookies } from "@/utils/cookieUtils"
export interface ProxySettings {
- PROXY_BASE_URL: string | null;
- PROXY_LOGOUT_URL: string | null;
- DEFAULT_TEAM_DISABLED: boolean;
- SSO_ENABLED: boolean;
- DISABLE_EXPENSIVE_DB_QUERIES: boolean;
- NUM_SPEND_LOGS_ROWS: number;
+ PROXY_BASE_URL: string | null
+ PROXY_LOGOUT_URL: string | null
+ DEFAULT_TEAM_DISABLED: boolean
+ SSO_ENABLED: boolean
+ DISABLE_EXPENSIVE_DB_QUERIES: boolean
+ NUM_SPEND_LOGS_ROWS: number
}
-
export type UserInfo = {
- models: string[];
- max_budget?: number | null;
- spend: number;
+ models: string[]
+ max_budget?: number | null
+ spend: number
}
function getCookie(name: string) {
console.log("COOKIES", document.cookie)
- const cookieValue = document.cookie
- .split('; ')
- .find(row => row.startsWith(name + '='));
- return cookieValue ? cookieValue.split('=')[1] : null;
+ const cookieValue = document.cookie.split("; ").find((row) => row.startsWith(name + "="))
+ return cookieValue ? cookieValue.split("=")[1] : null
}
interface UserDashboardProps {
- userID: string | null;
- userRole: string | null;
- userEmail: string | null;
- teams: Team[] | null;
- keys: any[] | null;
- setUserRole: React.Dispatch<React.SetStateAction<string>>;
- setUserEmail: React.Dispatch<React.SetStateAction<string | null>>;
- setTeams: React.Dispatch<React.SetStateAction<Team[] | null>>;
- setKeys: React.Dispatch<React.SetStateAction<Object[] | null>>;
- premiumUser: boolean;
- organizations: Organization[] | null;
- addKey: (data: any) => void;
+ userID: string | null
+ userRole: string | null
+ userEmail: string | null
+ teams: Team[] | null
+ keys: any[] | null
+ setUserRole: React.Dispatch<React.SetStateAction<string>>
+ setUserEmail: React.Dispatch<React.SetStateAction<string | null>>
+ setTeams: React.Dispatch<React.SetStateAction<Team[] | null>>
+ setKeys: React.Dispatch<React.SetStateAction<Object[] | null>>
+ premiumUser: boolean
+ organizations: Organization[] | null
+ addKey: (data: any) => void
createClicked: boolean
}
type TeamInterface = {
- models: any[];
- team_id: null;
- team_alias: String;
-};
+ models: any[]
+ team_id: null
+ team_alias: String
+}
const UserDashboard: React.FC<UserDashboardProps> = ({
userID,
@@ -84,63 +81,61 @@ const UserDashboard: React.FC<UserDashboardProps> = ({
premiumUser,
organizations,
addKey,
- createClicked
+ createClicked,
}) => {
- const [userSpendData, setUserSpendData] = useState<UserInfo | null>(
- null
- );
- const [currentOrg, setCurrentOrg] = useState<Organization | null>(null);
+ const [userSpendData, setUserSpendData] = useState<UserInfo | null>(null)
+ const [currentOrg, setCurrentOrg] = useState<Organization | null>(null)
// Assuming useSearchParams() hook exists and works in your setup
- const searchParams = useSearchParams()!;
+ const searchParams = useSearchParams()!
- const token = getCookie('token');
+ const token = getCookie("token")
- const invitation_id = searchParams.get("invitation_id");
+ const invitation_id = searchParams.get("invitation_id")
- const [accessToken, setAccessToken] = useState<string | null>(null);
- const [teamSpend, setTeamSpend] = useState<number | null>(null);
- const [userModels, setUserModels] = useState<string[]>([]);
- const [proxySettings, setProxySettings] = useState<ProxySettings | null>(null);
+ const [accessToken, setAccessToken] = useState<string | null>(null)
+ const [teamSpend, setTeamSpend] = useState<number | null>(null)
+ const [userModels, setUserModels] = useState<string[]>([])
+ const [proxySettings, setProxySettings] = useState<ProxySettings | null>(null)
const defaultTeam: TeamInterface = {
models: [],
team_alias: "Default Team",
team_id: null,
- };
- const [selectedTeam, setSelectedTeam] = useState<any | null>(null);
- const [selectedKeyAlias, setSelectedKeyAlias] = useState<string | null>(null);
+ }
+ const [selectedTeam, setSelectedTeam] = useState<any | null>(null)
+ const [selectedKeyAlias, setSelectedKeyAlias] = useState<string | null>(null)
// check if window is not undefined
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", function () {
// Clear session storage
- sessionStorage.clear();
- });
+ sessionStorage.clear()
+ })
}
function formatUserRole(userRole: string) {
if (!userRole) {
- return "Undefined Role";
+ return "Undefined Role"
}
- console.log(`Received user role: ${userRole}`);
+ console.log(`Received user role: ${userRole}`)
switch (userRole.toLowerCase()) {
case "app_owner":
- return "App Owner";
+ return "App Owner"
case "demo_app_owner":
- return "App Owner";
+ return "App Owner"
case "app_admin":
- return "Admin";
+ return "Admin"
case "proxy_admin":
- return "Admin";
+ return "Admin"
case "proxy_admin_viewer":
- return "Admin Viewer";
+ return "Admin Viewer"
case "app_user":
- return "App User";
+ return "App User"
case "internal_user":
- return "Internal User";
+ return "Internal User"
case "internal_user_viewer":
- return "Internal Viewer";
+ return "Internal Viewer"
default:
- return "Unknown Role";
+ return "Unknown Role"
}
}
@@ -148,258 +143,217 @@ const UserDashboard: React.FC<UserDashboardProps> = ({
// Moved useEffect inside the component and used a condition to run fetch only if the params are available
useEffect(() => {
if (token) {
- const decoded = jwtDecode(token) as { [key: string]: any };
+ const decoded = jwtDecode(token) as { [key: string]: any }
if (decoded) {
// cast decoded to dictionary
- console.log("Decoded token:", decoded);
+ console.log("Decoded token:", decoded)
- console.log("Decoded key:", decoded.key);
+ console.log("Decoded key:", decoded.key)
// set accessToken
- setAccessToken(decoded.key);
+ setAccessToken(decoded.key)
// check if userRole is defined
if (decoded.user_role) {
- const formattedUserRole = formatUserRole(decoded.user_role);
- console.log("Decoded user_role:", formattedUserRole);
- setUserRole(formattedUserRole);
+ const formattedUserRole = formatUserRole(decoded.user_role)
+ console.log("Decoded user_role:", formattedUserRole)
+ setUserRole(formattedUserRole)
} else {
- console.log("User role not defined");
+ console.log("User role not defined")
}
if (decoded.user_email) {
- setUserEmail(decoded.user_email);
+ setUserEmail(decoded.user_email)
} else {
- console.log(`User Email is not set ${decoded}`);
+ console.log(`User Email is not set ${decoded}`)
}
}
}
if (userID && accessToken && userRole && !keys && !userSpendData) {
- const cachedUserModels = sessionStorage.getItem("userModels" + userID);
+ const cachedUserModels = sessionStorage.getItem("userModels" + userID)
if (cachedUserModels) {
- setUserModels(JSON.parse(cachedUserModels));
+ setUserModels(JSON.parse(cachedUserModels))
} else {
console.log(`currentOrg: ${JSON.stringify(currentOrg)}`)
const fetchData = async () => {
try {
- const proxy_settings: ProxySettings = await getProxyUISettings(accessToken);
- setProxySettings(proxy_settings);
-
- const response = await userInfoCall(
- accessToken,
- userID,
- userRole,
- false,
- null,
- null
- );
-
-
- setUserSpendData(response["user_info"]);
+ const proxy_settings: ProxySettings = await getProxyUISettings(accessToken)
+ setProxySettings(proxy_settings)
+
+ const response = await userInfoCall(accessToken, userID, userRole, false, null, null)
+
+ setUserSpendData(response["user_info"])
console.log(`userSpendData: ${JSON.stringify(userSpendData)}`)
-
// set keys for admin and users
if (!response?.teams[0].keys) {
- setKeys(response["keys"]);
+ setKeys(response["keys"])
} else {
setKeys(
response["keys"].concat(
response.teams
.filter((team: any) => userRole === "Admin" || team.user_id === userID)
- .flatMap((team: any) => team.keys)
- )
- );
-
+ .flatMap((team: any) => team.keys),
+ ),
+ )
}
- sessionStorage.setItem(
- "userData" + userID,
- JSON.stringify(response["keys"])
- );
- sessionStorage.setItem(
- "userSpendData" + userID,
- JSON.stringify(response["user_info"])
- );
-
- const model_available = await modelAvailableCall(
- accessToken,
- userID,
- userRole
- );
+ sessionStorage.setItem("userData" + userID, JSON.stringify(response["keys"]))
+ sessionStorage.setItem("userSpendData" + userID, JSON.stringify(response["user_info"]))
+
+ const model_available = await modelAvailableCall(accessToken, userID, userRole)
// loop through model_info["data"] and create an array of element.model_name
- let available_model_names = model_available["data"].map(
- (element: { id: string }) => element.id
- );
- console.log("available_model_names:", available_model_names);
- setUserModels(available_model_names);
-
- console.log("userModels:", userModels);
-
- sessionStorage.setItem(
- "userModels" + userID,
- JSON.stringify(available_model_names)
- );
+ let available_model_names = model_available["data"].map((element: { id: string }) => element.id)
+ console.log("available_model_names:", available_model_names)
+ setUserModels(available_model_names)
+
+ console.log("userModels:", userModels)
+
+ sessionStorage.setItem("userModels" + userID, JSON.stringify(available_model_names))
} catch (error: any) {
- console.error("There was an error fetching the data", error);
+ console.error("There was an error fetching the data", error)
if (error.message.includes("Invalid proxy server token passed")) {
- gotoLogin();
+ gotoLogin()
}
// Optionally, update your UI to reflect the error state here as well
}
- };
- fetchData();
- fetchTeams(accessToken, userID, userRole, currentOrg, setTeams);
+ }
+ fetchData()
+ fetchTeams(accessToken, userID, userRole, currentOrg, setTeams)
}
}
- }, [userID, token, accessToken, keys, userRole]);
-
+ }, [userID, token, accessToken, keys, userRole])
useEffect(() => {
// check key health - if it's invalid, redirect to login
if (accessToken) {
const fetchKeyInfo = async () => {
try {
- const keyInfo = await keyInfoCall(accessToken, [accessToken]);
- console.log("keyInfo: ", keyInfo);
+ const keyInfo = await keyInfoCall(accessToken, [accessToken])
+ console.log("keyInfo: ", keyInfo)
} catch (error: any) {
if (error.message.includes("Invalid proxy server token passed")) {
- gotoLogin();
+ gotoLogin()
}
}
}
- fetchKeyInfo();
+ fetchKeyInfo()
}
- }, [accessToken]);
+ }, [accessToken])
useEffect(() => {
- console.log(`currentOrg: ${JSON.stringify(currentOrg)}, accessToken: ${accessToken}, userID: ${userID}, userRole: ${userRole}`)
+ console.log(
+ `currentOrg: ${JSON.stringify(currentOrg)}, accessToken: ${accessToken}, userID: ${userID}, userRole: ${userRole}`,
+ )
if (accessToken) {
console.log(`fetching teams`)
- fetchTeams(accessToken, userID, userRole, currentOrg, setTeams);
+ fetchTeams(accessToken, userID, userRole, currentOrg, setTeams)
}
- }, [currentOrg]);
+ }, [currentOrg])
useEffect(() => {
// This code will run every time selectedTeam changes
- if (
- keys !== null &&
- selectedTeam !== null &&
- selectedTeam !== undefined &&
- selectedTeam.team_id !== null
- ) {
- let sum = 0;
+ if (keys !== null && selectedTeam !== null && selectedTeam !== undefined && selectedTeam.team_id !== null) {
+ let sum = 0
console.log(`keys: ${JSON.stringify(keys)}`)
for (const key of keys) {
- if (
- selectedTeam.hasOwnProperty("team_id") &&
- key.team_id !== null &&
- key.team_id === selectedTeam.team_id
- ) {
- sum += key.spend;
+ if (selectedTeam.hasOwnProperty("team_id") && key.team_id !== null && key.team_id === selectedTeam.team_id) {
+ sum += key.spend
}
}
console.log(`sum: ${sum}`)
- setTeamSpend(sum);
+ setTeamSpend(sum)
} else if (keys !== null) {
// sum the keys which don't have team-id set (default team)
- let sum = 0;
+ let sum = 0
for (const key of keys) {
- sum += key.spend;
+ sum += key.spend
}
- setTeamSpend(sum);
+ setTeamSpend(sum)
}
- }, [selectedTeam]);
-
+ }, [selectedTeam])
if (invitation_id != null) {
- return (
- <Onboarding></Onboarding>
- )
+ return <Onboarding></Onboarding>
}
function gotoLogin() {
// Clear token cookies using the utility function
- clearTokenCookies();
+ clearTokenCookies()
+
+ const baseUrl = getProxyBaseUrl()
- const baseUrl = getProxyBaseUrl();
+ console.log("proxyBaseUrl:", baseUrl)
- console.log("proxyBaseUrl:", baseUrl);
-
- const url = baseUrl
- ? `${baseUrl}/sso/key/generate`
- : `/sso/key/generate`;
+ const url = baseUrl ? `${baseUrl}/sso/key/generate` : `/sso/key/generate`
- console.log("Full URL:", url);
- window.location.href = url;
+ console.log("Full URL:", url)
+ window.location.href = url
- return null;
+ return null
}
if (token == null) {
- // user is not logged in as yet
- console.log("All cookies before redirect:", document.cookie);
-
+ // user is not logged in as yet
+ console.log("All cookies before redirect:", document.cookie)
+
// Clear token cookies using the utility function
- gotoLogin();
- return null;
+ gotoLogin()
+ return null
} else {
// Check if token is expired
try {
- const decoded = jwtDecode(token) as { [key: string]: any };
- console.log("Decoded token:", decoded);
- const expTime = decoded.exp;
- const currentTime = Math.floor(Date.now() / 1000);
-
+ const decoded = jwtDecode(token) as { [key: string]: any }
+ console.log("Decoded token:", decoded)
+ const expTime = decoded.exp
+ const currentTime = Math.floor(Date.now() / 1000)
+
if (expTime && currentTime >= expTime) {
- console.log("Token expired, redirecting to login");
-
- gotoLogin();
-
- return null;
+ console.log("Token expired, redirecting to login")
+
+ gotoLogin()
+
+ return null
}
} catch (error) {
- console.error("Error decoding token:", error);
+ console.error("Error decoding token:", error)
// If there's an error decoding the token, consider it invalid
- clearTokenCookies();
-
- gotoLogin();
-
- return null;
+ clearTokenCookies()
+
+ gotoLogin()
+
+ return null
}
-
+
if (accessToken == null) {
- return null;
+ return null
}
}
if (userID == null) {
- return (
- <h1>User ID is not set</h1>
- );
+ return <h1>User ID is not set</h1>
}
-
if (userRole == null) {
- setUserRole("App Owner");
+ setUserRole("App Owner")
}
if (userRole && userRole == "Admin Viewer") {
- const { Title, Paragraph } = Typography;
+ const { Title, Paragraph } = Typography
return (
<div>
<Title level={1}>Access Denied</Title>
<Paragraph>Ask your proxy admin for access to create keys</Paragraph>
</div>
- );
+ )
}
- console.log("inside user dashboard, selected team", selectedTeam);
- console.log("All cookies after redirect:", document.cookie);
+ console.log("inside user dashboard, selected team", selectedTeam)
+ console.log("All cookies after redirect:", document.cookie)
return (
<div className="w-full mx-4 h-[75vh]">
<Grid numItems={1} className="gap-2 p-8 w-full mt-2">
<Col numColSpan={1} className="flex flex-col gap-2">
- <CreateKey
+ <CreateKey
key={selectedTeam ? selectedTeam.team_id : null}
userID={userID}
team={selectedTeam as Team | null}
@@ -431,7 +385,7 @@ const UserDashboard: React.FC<UserDashboardProps> = ({
</Col>
</Grid>
</div>
- );
-};
+ )
+}
-export default UserDashboard;
+export default UserDashboard
diff --git a/ui/litellm-dashboard/src/components/view_logs/SessionView.tsx b/ui/litellm-dashboard/src/components/view_logs/SessionView.tsx
index b2b2c3138e7..bb655ba0e8f 100644
--- a/ui/litellm-dashboard/src/components/view_logs/SessionView.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/SessionView.tsx
@@ -1,63 +1,61 @@
-import React, { useState } from 'react';
-import { LogEntry } from './columns';
-import { DataTable } from './table';
-import { columns } from './columns';
-import { Card, Title, Text, Metric, AreaChart } from '@tremor/react';
-import { RequestViewer } from './index';
-import { formatNumberWithCommas } from '@/utils/dataUtils';
+import React, { useState } from "react"
+import { LogEntry } from "./columns"
+import { DataTable } from "./table"
+import { columns } from "./columns"
+import { Card, Title, Text, Metric, AreaChart, Button as TremorButton } from "@tremor/react"
+import { RequestViewer } from "./index"
+import { formatNumberWithCommas } from "@/utils/dataUtils"
+import { ArrowLeftIcon } from "@heroicons/react/outline"
interface SessionViewProps {
- sessionId: string;
- logs: LogEntry[];
- onBack: () => void;
+ sessionId: string
+ logs: LogEntry[]
+ onBack: () => void
}
export const SessionView: React.FC<SessionViewProps> = ({ sessionId, logs, onBack }) => {
// Track which log row is expanded
- const [expandedRequestId, setExpandedRequestId] = useState<string | null>(null);
+ const [expandedRequestId, setExpandedRequestId] = useState<string | null>(null)
// Calculate session metrics
- const totalCost = logs.reduce((sum, log) => sum + (log.spend || 0), 0);
- const totalTokens = logs.reduce((sum, log) => sum + (log.total_tokens || 0), 0);
- const startTime = logs.length > 0 ? new Date(logs[0].startTime) : new Date();
- const endTime = logs.length > 0 ? new Date(logs[logs.length - 1].endTime) : new Date();
- const durationMs = endTime.getTime() - startTime.getTime();
- const durationSec = (durationMs / 1000).toFixed(2);
-
+ const totalCost = logs.reduce((sum, log) => sum + (log.spend || 0), 0)
+ const totalTokens = logs.reduce((sum, log) => sum + (log.total_tokens || 0), 0)
+ const startTime = logs.length > 0 ? new Date(logs[0].startTime) : new Date()
+ const endTime = logs.length > 0 ? new Date(logs[logs.length - 1].endTime) : new Date()
+ const durationMs = endTime.getTime() - startTime.getTime()
+ const durationSec = (durationMs / 1000).toFixed(2)
+
// Prepare data for the timeline chart
- const timelineData = logs.map(log => ({
+ const timelineData = logs.map((log) => ({
time: new Date(log.startTime).toISOString(),
tokens: log.total_tokens || 0,
cost: log.spend || 0,
- }));
+ }))
return (
<div className="space-y-6">
{/* Header with back button */}
<div className="mb-8">
- <div className="flex items-center space-x-4">
- <button
- onClick={onBack}
- className="flex items-center text-gray-600 hover:text-gray-900 transition-colors"
- >
- <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
- </svg>
- Back to All Logs
- </button>
- </div>
+ <TremorButton icon={ArrowLeftIcon} variant="light" onClick={onBack} className="mb-4">
+ Back to All Logs
+ </TremorButton>
<div className="mt-4">
<h1 className="text-2xl font-semibold text-gray-900">Session Details</h1>
<div className="space-y-2">
<p className="text-sm text-gray-500 font-mono">{sessionId}</p>
- <a
- href="https://docs.litellm.ai/docs/proxy/ui_logs_sessions"
- target="_blank"
- rel="noopener noreferrer"
+ <a
+ href="https://docs.litellm.ai/docs/proxy/ui_logs_sessions"
+ target="_blank"
+ rel="noopener noreferrer"
className="text-sm text-blue-600 hover:text-blue-800 flex items-center gap-1"
>
Get started with session management here
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
+ />
</svg>
</a>
</div>
@@ -80,17 +78,17 @@ export const SessionView: React.FC<SessionViewProps> = ({ sessionId, logs, onBac
</Card>
</div>
{/* Request Timeline */}
- <Title>Session Logs</Title>
- <div className="mt-4">
- <DataTable
- columns={columns}
- data={logs}
- renderSubComponent={RequestViewer}
- getRowCanExpand={() => true}
- loadingMessage="Loading logs..."
- noDataMessage="No logs found"
- />
- </div>
+ <Title>Session Logs</Title>
+ <div className="mt-4">
+ <DataTable
+ columns={columns}
+ data={logs}
+ renderSubComponent={RequestViewer}
+ getRowCanExpand={() => true}
+ loadingMessage="Loading logs..."
+ noDataMessage="No logs found"
+ />
+ </div>
</div>
- );
-};
\ No newline at end of file
+ )
+}
diff --git a/ui/litellm-dashboard/src/components/view_users.tsx b/ui/litellm-dashboard/src/components/view_users.tsx
index ff9dab752eb..c9ace5d2045 100644
--- a/ui/litellm-dashboard/src/components/view_users.tsx
+++ b/ui/litellm-dashboard/src/components/view_users.tsx
@@ -1,15 +1,7 @@
-import React, { useState, useEffect, useCallback, useRef } from "react";
-import {
- Tab,
- TabGroup,
- TabList,
- TabPanels,
- TabPanel,
- Select,
- SelectItem,
-} from "@tremor/react";
+import React, { useState, useEffect, useCallback, useRef } from "react"
+import { Tab, TabGroup, TabList, TabPanels, TabPanel, Select, SelectItem } from "@tremor/react"
-import { message } from "antd";
+import { message } from "antd"
import {
userInfoCall,
@@ -19,48 +11,47 @@ import {
UserListResponse,
invitationCreateCall,
getProxyBaseUrl,
-} from "./networking";
-import { Button } from "@tremor/react";
-import CreateUser from "./create_user_button";
-import EditUserModal from "./edit_user";
-import OnboardingModal from "./onboarding_link";
-import { InvitationLink } from "./onboarding_link";
-
-import { userDeleteCall } from "./networking";
-import { columns } from "./view_users/columns";
-import { UserDataTable } from "./view_users/table";
-import { UserInfo } from "./view_users/types";
-import SSOSettings from "./SSOSettings";
-import debounce from "lodash/debounce";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
-import { updateExistingKeys } from "@/utils/dataUtils";
-import { useDebouncedState } from '@tanstack/react-pacer/debouncer'
+} from "./networking"
+import { Button } from "@tremor/react"
+import CreateUser from "./create_user_button"
+import EditUserModal from "./edit_user"
+import OnboardingModal from "./onboarding_link"
+import { InvitationLink } from "./onboarding_link"
+
+import { userDeleteCall } from "./networking"
+import { columns } from "./view_users/columns"
+import { UserDataTable } from "./view_users/table"
+import { UserInfo } from "./view_users/types"
+import SSOSettings from "./SSOSettings"
+import debounce from "lodash/debounce"
+import { useQuery, useQueryClient } from "@tanstack/react-query"
+import { updateExistingKeys } from "@/utils/dataUtils"
+import { useDebouncedState } from "@tanstack/react-pacer/debouncer"
interface ViewUserDashboardProps {
- accessToken: string | null;
- token: string | null;
- keys: any[] | null;
- userRole: string | null;
- userID: string | null;
- teams: any[] | null;
- setKeys: React.Dispatch<React.SetStateAction<Object[] | null>>;
+ accessToken: string | null
+ token: string | null
+ keys: any[] | null
+ userRole: string | null
+ userID: string | null
+ teams: any[] | null
+ setKeys: React.Dispatch<React.SetStateAction<Object[] | null>>
}
interface FilterState {
- email: string;
- user_id: string;
- user_role: string;
- sso_user_id: string;
- team: string;
- model: string;
- min_spend: number | null;
- max_spend: number | null;
- sort_by: string;
- sort_order: 'asc' | 'desc';
+ email: string
+ user_id: string
+ user_role: string
+ sso_user_id: string
+ team: string
+ model: string
+ min_spend: number | null
+ max_spend: number | null
+ sort_by: string
+ sort_order: "asc" | "desc"
}
-
-const DEFAULT_PAGE_SIZE = 25;
+const DEFAULT_PAGE_SIZE = 25
const initialFilters: FilterState = {
email: "",
@@ -72,36 +63,28 @@ const initialFilters: FilterState = {
min_spend: null,
max_spend: null,
sort_by: "created_at",
- sort_order: "desc"
+ sort_order: "desc",
}
-const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
- accessToken,
- token,
- userRole,
- userID,
- teams,
-}) => {
- const queryClient = useQueryClient();
- const [currentPage, setCurrentPage] = useState(1);
- const [editModalVisible, setEditModalVisible] = useState(false);
- const [selectedUser, setSelectedUser] = useState<UserInfo | null>(null);
- const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
- const [userToDelete, setUserToDelete] = useState<string | null>(null);
- const [activeTab, setActiveTab] = useState("users");
- const [filters, setFilters] = useState<FilterState>(initialFilters);
+const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({ accessToken, token, userRole, userID, teams }) => {
+ const queryClient = useQueryClient()
+ const [currentPage, setCurrentPage] = useState(1)
+ const [editModalVisible, setEditModalVisible] = useState(false)
+ const [selectedUser, setSelectedUser] = useState<UserInfo | null>(null)
+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
+ const [userToDelete, setUserToDelete] = useState<string | null>(null)
+ const [activeTab, setActiveTab] = useState("users")
+ const [filters, setFilters] = useState<FilterState>(initialFilters)
const [debouncedFilters, setDebouncedFilters, debouncer] = useDebouncedState(filters, { wait: 300 })
- const [showFilters, setShowFilters] = useState(false);
- const [isInvitationLinkModalVisible, setIsInvitationLinkModalVisible] =
- useState(false);
- const [invitationLinkData, setInvitationLinkData] =
- useState<InvitationLink | null>(null);
- const [baseUrl, setBaseUrl] = useState<string | null>(null);
+ const [showFilters, setShowFilters] = useState(false)
+ const [isInvitationLinkModalVisible, setIsInvitationLinkModalVisible] = useState(false)
+ const [invitationLinkData, setInvitationLinkData] = useState<InvitationLink | null>(null)
+ const [baseUrl, setBaseUrl] = useState<string | null>(null)
const handleDelete = (userId: string) => {
- setUserToDelete(userId);
- setIsDeleteModalOpen(true);
- };
+ setUserToDelete(userId)
+ setIsDeleteModalOpen(true)
+ }
useEffect(() => {
return () => {
@@ -110,106 +93,106 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
}, [debouncer])
useEffect(() => {
- setBaseUrl(getProxyBaseUrl());
- }, []);
+ setBaseUrl(getProxyBaseUrl())
+ }, [])
const updateFilters = (update: Partial<FilterState>) => {
setFilters((previousFilters) => {
- const newFilters = {...previousFilters, ...update };
- setDebouncedFilters(newFilters);
- return newFilters;
+ const newFilters = { ...previousFilters, ...update }
+ setDebouncedFilters(newFilters)
+ return newFilters
})
- };
+ }
- const handleSortChange = (sortBy: string, sortOrder: 'asc' | 'desc') => {
- updateFilters({ sort_by: sortBy, sort_order: sortOrder });
- };
+ const handleSortChange = (sortBy: string, sortOrder: "asc" | "desc") => {
+ updateFilters({ sort_by: sortBy, sort_order: sortOrder })
+ }
const handleResetPassword = async (userId: string) => {
if (!accessToken) {
- message.error("Access token not found");
- return;
+ message.error("Access token not found")
+ return
}
try {
- message.success("Generating password reset link...");
- const data = await invitationCreateCall(accessToken, userId);
- setInvitationLinkData(data);
- setIsInvitationLinkModalVisible(true);
+ message.success("Generating password reset link...")
+ const data = await invitationCreateCall(accessToken, userId)
+ setInvitationLinkData(data)
+ setIsInvitationLinkModalVisible(true)
} catch (error) {
- message.error("Failed to generate password reset link");
+ message.error("Failed to generate password reset link")
}
- };
+ }
const confirmDelete = async () => {
if (userToDelete && accessToken) {
try {
- await userDeleteCall(accessToken, [userToDelete]);
+ await userDeleteCall(accessToken, [userToDelete])
// Update the user list after deletion
- queryClient.setQueriesData<UserListResponse>({ queryKey: ['userList'] }, (previousData) => {
- if (previousData === undefined) return previousData;
- const updatedUsers = previousData.users.filter(user => user.user_id !== userToDelete);
- return { ...previousData, users: updatedUsers };
+ queryClient.setQueriesData<UserListResponse>({ queryKey: ["userList"] }, (previousData) => {
+ if (previousData === undefined) return previousData
+ const updatedUsers = previousData.users.filter((user) => user.user_id !== userToDelete)
+ return { ...previousData, users: updatedUsers }
})
-
- message.success("User deleted successfully");
+
+ message.success("User deleted successfully")
} catch (error) {
- console.error("Error deleting user:", error);
- message.error("Failed to delete user");
+ console.error("Error deleting user:", error)
+ message.error("Failed to delete user")
}
}
- setIsDeleteModalOpen(false);
- setUserToDelete(null);
- };
+ setIsDeleteModalOpen(false)
+ setUserToDelete(null)
+ }
const cancelDelete = () => {
- setIsDeleteModalOpen(false);
- setUserToDelete(null);
- };
+ setIsDeleteModalOpen(false)
+ setUserToDelete(null)
+ }
const handleEditCancel = async () => {
- setSelectedUser(null);
- setEditModalVisible(false);
- };
+ setSelectedUser(null)
+ setEditModalVisible(false)
+ }
const handleEditSubmit = async (editedUser: any) => {
- console.log("inside handleEditSubmit:", editedUser);
+ console.log("inside handleEditSubmit:", editedUser)
if (!accessToken || !token || !userRole || !userID) {
- return;
+ return
}
try {
- const response = await userUpdateUserCall(accessToken, editedUser, null);
- queryClient.setQueriesData<UserListResponse>({ queryKey: ['userList'] }, (previousData) => {
- if (previousData === undefined) return previousData;
- const updatedUsers = previousData.users.map(user => {
+ const response = await userUpdateUserCall(accessToken, editedUser, null)
+ queryClient.setQueriesData<UserListResponse>({ queryKey: ["userList"] }, (previousData) => {
+ if (previousData === undefined) return previousData
+ const updatedUsers = previousData.users.map((user) => {
if (user.user_id === response.data.user_id) {
- return updateExistingKeys(user, response.data);
+ return updateExistingKeys(user, response.data)
}
- return user;
- });
-
- return { ...previousData, users: updatedUsers };
+ return user
+ })
+
+ return { ...previousData, users: updatedUsers }
})
- message.success(`User ${editedUser.user_id} updated successfully`);
+ message.success(`User ${editedUser.user_id} updated successfully`)
} catch (error) {
- console.error("There was an error updating the user", error);
+ console.error("There was an error updating the user", error)
}
- setSelectedUser(null);
- setEditModalVisible(false);
+ setSelectedUser(null)
+ setEditModalVisible(false)
// Close the modal
- };
+ }
const handlePageChange = async (newPage: number) => {
- setCurrentPage(newPage);
- };
+ setCurrentPage(newPage)
+ }
const userListQuery = useQuery({
- queryKey: ['userList', { debouncedFilter: debouncedFilters, currentPage }],
+ queryKey: ["userList", { debouncedFilter: debouncedFilters, currentPage }],
queryFn: async () => {
- if (!accessToken) throw new Error('Access token required');
+ if (!accessToken) throw new Error("Access token required")
return await userListCall(
accessToken,
@@ -221,23 +204,23 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
debouncedFilters.team || null,
debouncedFilters.sso_user_id || null,
debouncedFilters.sort_by,
- debouncedFilters.sort_order
- );
+ debouncedFilters.sort_order,
+ )
},
enabled: Boolean(accessToken && token && userRole && userID),
- placeholderData: (previousData) => previousData
- });
+ placeholderData: (previousData) => previousData,
+ })
const userListResponse = userListQuery.data
const userRolesQuery = useQuery<Record<string, Record<string, string>>>({
- queryKey: ['userRoles'],
+ queryKey: ["userRoles"],
initialData: () => ({}),
queryFn: async () => {
- if (!accessToken) throw new Error('Access token required');
- return await getPossibleUserRoles(accessToken);
+ if (!accessToken) throw new Error("Access token required")
+ return await getPossibleUserRoles(accessToken)
},
enabled: Boolean(accessToken && token && userRole && userID),
- });
+ })
const possibleUIRoles = userRolesQuery.data
if (userListQuery.isLoading) {
@@ -245,40 +228,34 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
}
if (!accessToken || !token || !userRole || !userID) {
- return <div>Loading...</div>;
+ return <div>Loading...</div>
}
const tableColumns = columns(
possibleUIRoles,
(user) => {
- setSelectedUser(user);
- setEditModalVisible(true);
+ setSelectedUser(user)
+ setEditModalVisible(true)
},
handleDelete,
handleResetPassword,
- () => {} // placeholder function, will be overridden in UserDataTable
- );
+ () => {}, // placeholder function, will be overridden in UserDataTable
+ )
return (
<div className="w-full p-6">
<div className="flex items-center justify-between mb-4">
- <h1 className="text-xl font-semibold">Users</h1>
<div className="flex space-x-3">
- <CreateUser
- userID={userID}
- accessToken={accessToken}
- teams={teams}
- possibleUIRoles={possibleUIRoles}
- />
+ <CreateUser userID={userID} accessToken={accessToken} teams={teams} possibleUIRoles={possibleUIRoles} />
</div>
</div>
-
+
<TabGroup defaultIndex={0} onIndexChange={(index) => setActiveTab(index === 0 ? "users" : "settings")}>
<TabList className="mb-4">
<Tab>Users</Tab>
<Tab>Default User Settings</Tab>
</TabList>
-
+
<TabPanels>
<TabPanel>
<div className="bg-white rounded-lg shadow">
@@ -312,15 +289,10 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
{/* Filter Button */}
<button
- className={`px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ${showFilters ? 'bg-gray-100' : ''}`}
+ className={`px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ${showFilters ? "bg-gray-100" : ""}`}
onClick={() => setShowFilters(!showFilters)}
>
- <svg
- className="w-4 h-4"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round"
strokeLinejoin="round"
@@ -338,15 +310,10 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
<button
className="px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2"
onClick={() => {
- updateFilters(initialFilters);
+ updateFilters(initialFilters)
}}
>
- <svg
- className="w-4 h-4"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- >
+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round"
strokeLinejoin="round"
@@ -368,7 +335,7 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
placeholder="Filter by User ID"
className="w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
value={filters.user_id}
- onChange={(e) => updateFilters({ user_id : e.target.value })}
+ onChange={(e) => updateFilters({ user_id: e.target.value })}
/>
<svg
className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500"
@@ -414,7 +381,7 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
))}
</Select>
</div>
-
+
{/* SSO ID Search */}
<div className="relative w-64">
<input
@@ -422,7 +389,7 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
placeholder="Filter by SSO ID"
className="w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
value={filters.sso_user_id}
- onChange={(e) => updateFilters({ sso_user_id : e.target.value })}
+ onChange={(e) => updateFilters({ sso_user_id: e.target.value })}
/>
</div>
</div>
@@ -437,23 +404,18 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
: 0}{" "}
-{" "}
{userListResponse && userListResponse.users
- ? Math.min(
- userListResponse.page * userListResponse.page_size,
- userListResponse.total
- )
+ ? Math.min(userListResponse.page * userListResponse.page_size, userListResponse.total)
: 0}{" "}
of {userListResponse ? userListResponse.total : 0} results
</span>
-
+
{/* Pagination Buttons */}
<div className="flex space-x-2">
<button
onClick={() => handlePageChange(currentPage - 1)}
disabled={currentPage === 1}
className={`px-3 py-1 text-sm border rounded-md ${
- currentPage === 1
- ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
- : 'hover:bg-gray-50'
+ currentPage === 1 ? "bg-gray-100 text-gray-400 cursor-not-allowed" : "hover:bg-gray-50"
}`}
>
Previous
@@ -463,8 +425,8 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
disabled={!userListResponse || currentPage >= userListResponse.total_pages}
className={`px-3 py-1 text-sm border rounded-md ${
!userListResponse || currentPage >= userListResponse.total_pages
- ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
- : 'hover:bg-gray-50'
+ ? "bg-gray-100 text-gray-400 cursor-not-allowed"
+ : "hover:bg-gray-50"
}`}
>
Next
@@ -483,21 +445,26 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
onSortChange={handleSortChange}
currentSort={{
sortBy: filters.sort_by,
- sortOrder: filters.sort_order
+ sortOrder: filters.sort_order,
}}
possibleUIRoles={possibleUIRoles}
handleEdit={(user) => {
- setSelectedUser(user);
- setEditModalVisible(true);
+ setSelectedUser(user)
+ setEditModalVisible(true)
}}
handleDelete={handleDelete}
handleResetPassword={handleResetPassword}
/>
</div>
</TabPanel>
-
+
<TabPanel>
- <SSOSettings accessToken={accessToken} possibleUIRoles={possibleUIRoles} userID={userID} userRole={userRole}/>
+ <SSOSettings
+ accessToken={accessToken}
+ possibleUIRoles={possibleUIRoles}
+ userID={userID}
+ userRole={userRole}
+ />
</TabPanel>
</TabPanels>
</TabGroup>
@@ -515,18 +482,12 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
{isDeleteModalOpen && (
<div className="fixed z-10 inset-0 overflow-y-auto">
<div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
- <div
- className="fixed inset-0 transition-opacity"
- aria-hidden="true"
- >
+ <div className="fixed inset-0 transition-opacity" aria-hidden="true">
<div className="absolute inset-0 bg-gray-500 opacity-75"></div>
</div>
{/* Modal Panel */}
- <span
- className="hidden sm:inline-block sm:align-middle sm:h-screen"
- aria-hidden="true"
- >
+ <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">
&#8203;
</span>
@@ -535,16 +496,10 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
<div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div className="sm:flex sm:items-start">
<div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
- <h3 className="text-lg leading-6 font-medium text-gray-900">
- Delete User
- </h3>
+ <h3 className="text-lg leading-6 font-medium text-gray-900">Delete User</h3>
<div className="mt-2">
- <p className="text-sm text-gray-500">
- Are you sure you want to delete this user?
- </p>
- <p className="text-sm font-medium text-gray-900 mt-2">
- User ID: {userToDelete}
- </p>
+ <p className="text-sm text-gray-500">Are you sure you want to delete this user?</p>
+ <p className="text-sm font-medium text-gray-900 mt-2">User ID: {userToDelete}</p>
</div>
</div>
</div>
@@ -568,7 +523,7 @@ const ViewUserDashboard: React.FC<ViewUserDashboardProps> = ({
modalType="resetPassword"
/>
</div>
- );
-};
+ )
+}
-export default ViewUserDashboard;
+export default ViewUserDashboard
diff --git a/ui/litellm-dashboard/src/components/view_users/user_info_view.tsx b/ui/litellm-dashboard/src/components/view_users/user_info_view.tsx
index 482b932020c..b8fb64828c2 100644
--- a/ui/litellm-dashboard/src/components/view_users/user_info_view.tsx
+++ b/ui/litellm-dashboard/src/components/view_users/user_info_view.tsx
@@ -1,137 +1,131 @@
-import React, { useState } from "react";
+import React, { useState } from "react"
+import { Card, Text, Button, Grid, Col, Tab, TabList, TabGroup, TabPanel, TabPanels, Title, Badge } from "@tremor/react"
+import { ArrowLeftIcon, TrashIcon, RefreshIcon } from "@heroicons/react/outline"
import {
- Card,
- Text,
- Button,
- Grid,
- Col,
- Tab,
- TabList,
- TabGroup,
- TabPanel,
- TabPanels,
- Title,
- Badge,
-} from "@tremor/react";
-import { ArrowLeftIcon, TrashIcon, RefreshIcon } from "@heroicons/react/outline";
-import { userInfoCall, userDeleteCall, userUpdateUserCall, modelAvailableCall, invitationCreateCall, getProxyBaseUrl } from "../networking";
-import { message } from "antd";
-import { rolesWithWriteAccess } from '../../utils/roles';
-import { UserEditView } from "../user_edit_view";
-import OnboardingModal, { InvitationLink } from "../onboarding_link";
-import { formatNumberWithCommas } from "@/utils/dataUtils";
+ userInfoCall,
+ userDeleteCall,
+ userUpdateUserCall,
+ modelAvailableCall,
+ invitationCreateCall,
+ getProxyBaseUrl,
+} from "../networking"
+import { message } from "antd"
+import { rolesWithWriteAccess } from "../../utils/roles"
+import { UserEditView } from "../user_edit_view"
+import OnboardingModal, { InvitationLink } from "../onboarding_link"
+import { formatNumberWithCommas } from "@/utils/dataUtils"
interface UserInfoViewProps {
- userId: string;
- onClose: () => void;
- accessToken: string | null;
- userRole: string | null;
- onDelete?: () => void;
- possibleUIRoles: Record<string, Record<string, string>> | null;
- initialTab?: number; // 0 for Overview, 1 for Details
- startInEditMode?: boolean;
+ userId: string
+ onClose: () => void
+ accessToken: string | null
+ userRole: string | null
+ onDelete?: () => void
+ possibleUIRoles: Record<string, Record<string, string>> | null
+ initialTab?: number // 0 for Overview, 1 for Details
+ startInEditMode?: boolean
}
interface UserInfo {
- user_id: string;
+ user_id: string
user_info: {
- user_email: string | null;
- user_role: string | null;
- teams: any[] | null;
- models: string[] | null;
- max_budget: number | null;
- spend: number | null;
- metadata: Record<string, any> | null;
- created_at: string | null;
- updated_at: string | null;
- };
- keys: any[] | null;
- teams: any[] | null;
+ user_email: string | null
+ user_role: string | null
+ teams: any[] | null
+ models: string[] | null
+ max_budget: number | null
+ spend: number | null
+ metadata: Record<string, any> | null
+ created_at: string | null
+ updated_at: string | null
+ }
+ keys: any[] | null
+ teams: any[] | null
}
-export default function UserInfoView({
- userId,
- onClose,
- accessToken,
- userRole,
- onDelete,
+export default function UserInfoView({
+ userId,
+ onClose,
+ accessToken,
+ userRole,
+ onDelete,
possibleUIRoles,
initialTab = 0,
- startInEditMode = false
+ startInEditMode = false,
}: UserInfoViewProps) {
- const [userData, setUserData] = useState<UserInfo | null>(null);
- const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
- const [isLoading, setIsLoading] = useState(true);
- const [isEditing, setIsEditing] = useState(startInEditMode);
- const [userModels, setUserModels] = useState<string[]>([]);
- const [isInvitationLinkModalVisible, setIsInvitationLinkModalVisible] = useState(false);
- const [invitationLinkData, setInvitationLinkData] = useState<InvitationLink | null>(null);
- const [baseUrl, setBaseUrl] = useState<string | null>(null);
- const [activeTab, setActiveTab] = useState(initialTab);
+ const [userData, setUserData] = useState<UserInfo | null>(null)
+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
+ const [isLoading, setIsLoading] = useState(true)
+ const [isEditing, setIsEditing] = useState(startInEditMode)
+ const [userModels, setUserModels] = useState<string[]>([])
+ const [isInvitationLinkModalVisible, setIsInvitationLinkModalVisible] = useState(false)
+ const [invitationLinkData, setInvitationLinkData] = useState<InvitationLink | null>(null)
+ const [baseUrl, setBaseUrl] = useState<string | null>(null)
+ const [activeTab, setActiveTab] = useState(initialTab)
React.useEffect(() => {
- setBaseUrl(getProxyBaseUrl());
- }, []);
+ setBaseUrl(getProxyBaseUrl())
+ }, [])
React.useEffect(() => {
console.log(`userId: ${userId}, userRole: ${userRole}, accessToken: ${accessToken}`)
const fetchData = async () => {
try {
- if (!accessToken) return;
- const data = await userInfoCall(accessToken, userId, userRole || "", false, null, null, true);
- setUserData(data);
+ if (!accessToken) return
+ const data = await userInfoCall(accessToken, userId, userRole || "", false, null, null, true)
+ setUserData(data)
// Fetch available models
- const modelDataResponse = await modelAvailableCall(accessToken, userId, userRole || "");
- const availableModels = modelDataResponse.data.map((model: any) => model.id);
- setUserModels(availableModels);
+ const modelDataResponse = await modelAvailableCall(accessToken, userId, userRole || "")
+ const availableModels = modelDataResponse.data.map((model: any) => model.id)
+ setUserModels(availableModels)
} catch (error) {
- console.error("Error fetching user data:", error);
- message.error("Failed to fetch user data");
+ console.error("Error fetching user data:", error)
+ message.error("Failed to fetch user data")
} finally {
- setIsLoading(false);
+ setIsLoading(false)
}
- };
+ }
- fetchData();
- }, [accessToken, userId, userRole]);
+ fetchData()
+ }, [accessToken, userId, userRole])
const handleResetPassword = async () => {
if (!accessToken) {
- message.error("Access token not found");
- return;
+ message.error("Access token not found")
+ return
}
try {
- message.success("Generating password reset link...");
- const data = await invitationCreateCall(accessToken, userId);
- setInvitationLinkData(data);
- setIsInvitationLinkModalVisible(true);
+ message.success("Generating password reset link...")
+ const data = await invitationCreateCall(accessToken, userId)
+ setInvitationLinkData(data)
+ setIsInvitationLinkModalVisible(true)
} catch (error) {
- message.error("Failed to generate password reset link");
+ message.error("Failed to generate password reset link")
}
- };
+ }
const handleDelete = async () => {
try {
- if (!accessToken) return;
- await userDeleteCall(accessToken, [userId]);
- message.success("User deleted successfully");
+ if (!accessToken) return
+ await userDeleteCall(accessToken, [userId])
+ message.success("User deleted successfully")
if (onDelete) {
- onDelete();
+ onDelete()
}
- onClose();
+ onClose()
} catch (error) {
- console.error("Error deleting user:", error);
- message.error("Failed to delete user");
+ console.error("Error deleting user:", error)
+ message.error("Failed to delete user")
}
- };
+ }
const handleUserUpdate = async (formValues: Record<string, any>) => {
try {
- if (!accessToken || !userData) return;
+ if (!accessToken || !userData) return
+
+ const response = await userUpdateUserCall(accessToken, formValues, null)
- const response = await userUpdateUserCall(accessToken, formValues, null);
-
// Update local state with new values
setUserData({
...userData,
@@ -141,59 +135,44 @@ export default function UserInfoView({
models: formValues.models,
max_budget: formValues.max_budget,
metadata: formValues.metadata,
- }
- });
+ },
+ })
- message.success("User updated successfully");
- setIsEditing(false);
+ message.success("User updated successfully")
+ setIsEditing(false)
} catch (error) {
- console.error("Error updating user:", error);
- message.error("Failed to update user");
+ console.error("Error updating user:", error)
+ message.error("Failed to update user")
}
- };
+ }
if (isLoading) {
return (
<div className="p-4">
- <Button
- icon={ArrowLeftIcon}
- variant="light"
- onClick={onClose}
- className="mb-4"
- >
+ <Button icon={ArrowLeftIcon} variant="light" onClick={onClose} className="mb-4">
Back to Users
</Button>
<Text>Loading user data...</Text>
</div>
- );
+ )
}
if (!userData) {
return (
<div className="p-4">
- <Button
- icon={ArrowLeftIcon}
- variant="light"
- onClick={onClose}
- className="mb-4"
- >
+ <Button icon={ArrowLeftIcon} variant="light" onClick={onClose} className="mb-4">
Back to Users
</Button>
<Text>User not found</Text>
</div>
- );
+ )
}
return (
<div className="p-4">
<div className="flex justify-between items-center mb-6">
<div>
- <Button
- icon={ArrowLeftIcon}
- variant="light"
- onClick={onClose}
- className="mb-4"
- >
+ <Button icon={ArrowLeftIcon} variant="light" onClick={onClose} className="mb-4">
Back to Users
</Button>
<Title>{userData.user_info?.user_email || "User"}</Title>
@@ -201,12 +180,7 @@ export default function UserInfoView({
</div>
{userRole && rolesWithWriteAccess.includes(userRole) && (
<div className="flex items-center space-x-2">
- <Button
- icon={RefreshIcon}
- variant="secondary"
- onClick={handleResetPassword}
- className="flex items-center"
- >
+ <Button icon={RefreshIcon} variant="secondary" onClick={handleResetPassword} className="flex items-center">
Reset Password
</Button>
<Button
@@ -229,34 +203,26 @@ export default function UserInfoView({
<div className="absolute inset-0 bg-gray-500 opacity-75"></div>
</div>
- <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
+ <span className="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">
+ &#8203;
+ </span>
<div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
<div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div className="sm:flex sm:items-start">
<div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
- <h3 className="text-lg leading-6 font-medium text-gray-900">
- Delete User
- </h3>
+ <h3 className="text-lg leading-6 font-medium text-gray-900">Delete User</h3>
<div className="mt-2">
- <p className="text-sm text-gray-500">
- Are you sure you want to delete this user?
- </p>
+ <p className="text-sm text-gray-500">Are you sure you want to delete this user?</p>
</div>
</div>
</div>
</div>
<div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
- <Button
- onClick={handleDelete}
- color="red"
- className="ml-2"
- >
+ <Button onClick={handleDelete} color="red" className="ml-2">
Delete
</Button>
- <Button onClick={() => setIsDeleteModalOpen(false)}>
- Cancel
- </Button>
+ <Button onClick={() => setIsDeleteModalOpen(false)}>Cancel</Button>
</div>
</div>
</div>
@@ -277,7 +243,12 @@ export default function UserInfoView({
<Text>Spend</Text>
<div className="mt-2">
<Title>${formatNumberWithCommas(userData.user_info?.spend || 0, 4)}</Title>
- <Text>of {userData.user_info?.max_budget !== null ? `$${formatNumberWithCommas(userData.user_info.max_budget, 4)}` : "Unlimited"}</Text>
+ <Text>
+ of{" "}
+ {userData.user_info?.max_budget !== null
+ ? `$${formatNumberWithCommas(userData.user_info.max_budget, 4)}`
+ : "Unlimited"}
+ </Text>
</div>
</Card>
@@ -299,9 +270,7 @@ export default function UserInfoView({
<Text>Personal Models</Text>
<div className="mt-2">
{userData.user_info?.models?.length && userData.user_info?.models?.length > 0 ? (
- userData.user_info?.models?.map((model, index) => (
- <Text key={index}>{model}</Text>
- ))
+ userData.user_info?.models?.map((model, index) => <Text key={index}>{model}</Text>)
) : (
<Text>All proxy models</Text>
)}
@@ -340,7 +309,7 @@ export default function UserInfoView({
<Text className="font-medium">User ID</Text>
<Text className="font-mono">{userData.user_id}</Text>
</div>
-
+
<div>
<Text className="font-medium">Email</Text>
<Text>{userData.user_info?.user_email || "Not Set"}</Text>
@@ -353,12 +322,20 @@ export default function UserInfoView({
<div>
<Text className="font-medium">Created</Text>
- <Text>{userData.user_info?.created_at ? new Date(userData.user_info.created_at).toLocaleString() : "Unknown"}</Text>
+ <Text>
+ {userData.user_info?.created_at
+ ? new Date(userData.user_info.created_at).toLocaleString()
+ : "Unknown"}
+ </Text>
</div>
<div>
<Text className="font-medium">Last Updated</Text>
- <Text>{userData.user_info?.updated_at ? new Date(userData.user_info.updated_at).toLocaleString() : "Unknown"}</Text>
+ <Text>
+ {userData.user_info?.updated_at
+ ? new Date(userData.user_info.updated_at).toLocaleString()
+ : "Unknown"}
+ </Text>
</div>
<div>
@@ -366,10 +343,7 @@ export default function UserInfoView({
<div className="flex flex-wrap gap-2 mt-1">
{userData.teams?.length && userData.teams?.length > 0 ? (
userData.teams?.map((team, index) => (
- <span
- key={index}
- className="px-2 py-1 bg-blue-100 rounded text-xs"
- >
+ <span key={index} className="px-2 py-1 bg-blue-100 rounded text-xs">
{team.team_alias || team.team_id}
</span>
))
@@ -384,10 +358,7 @@ export default function UserInfoView({
<div className="flex flex-wrap gap-2 mt-1">
{userData.user_info?.models?.length && userData.user_info?.models?.length > 0 ? (
userData.user_info?.models?.map((model, index) => (
- <span
- key={index}
- className="px-2 py-1 bg-blue-100 rounded text-xs"
- >
+ <span key={index} className="px-2 py-1 bg-blue-100 rounded text-xs">
{model}
</span>
))
@@ -402,10 +373,7 @@ export default function UserInfoView({
<div className="flex flex-wrap gap-2 mt-1">
{userData.keys?.length && userData.keys?.length > 0 ? (
userData.keys.map((key, index) => (
- <span
- key={index}
- className="px-2 py-1 bg-green-100 rounded text-xs"
- >
+ <span key={index} className="px-2 py-1 bg-green-100 rounded text-xs">
{key.key_alias || key.token}
</span>
))
@@ -435,5 +403,5 @@ export default function UserInfoView({
modalType="resetPassword"
/>
</div>
- );
-}
\ No newline at end of file
+ )
+}