The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
refactor(teams.tsx): refactor to display all teams, across all orgs (#8565)
Krish Dholakiabdc1a7254283
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.pyindex 8c01c7495bb..9d56fc71256 100644--- a/litellm/integrations/prometheus.py+++ b/litellm/integrations/prometheus.py@@ -1442,6 +1442,7 @@ class PrometheusLogger(CustomLogger):key_alias=None,exclude_team_id=UI_SESSION_TOKEN_TEAM_ID,return_full_object=True,+ organization_id=None,)keys = key_list_response.get("keys", [])total_count = key_list_response.get("total_count")diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.pyindex d7b939e0661..9a1cd56d07b 100644--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@ -1790,6 +1790,7 @@ async def list_keys("team_id","key_alias","return_full_object",+ "organization_id",}unsupported_params = set(request.query_params.keys()) - supported_paramsif unsupported_params:@@ -1829,6 +1830,7 @@ async def list_keys(team_id=team_id,key_alias=key_alias,return_full_object=return_full_object,+ organization_id=organization_id,)verbose_proxy_logger.debug("Successfully prepared response")@@ -1860,6 +1862,7 @@ async def _list_key_helper(size: int,user_id: Optional[str],team_id: Optional[str],+ organization_id: Optional[str],key_alias: Optional[str],exclude_team_id: Optional[str] = None,return_full_object: bool = False,@@ -1897,6 +1900,8 @@ async def _list_key_helper(where["key_alias"] = key_aliasif exclude_team_id and isinstance(exclude_team_id, str):where["team_id"] = {"not": exclude_team_id}+ if organization_id and isinstance(organization_id, str):+ where["organization_id"] = organization_idverbose_proxy_logger.debug(f"Filter conditions: {where}")diff --git a/ui/litellm-dashboard/src/app/page.tsx b/ui/litellm-dashboard/src/app/page.tsxindex 2abe45b94fc..d4f99161df3 100644--- a/ui/litellm-dashboard/src/app/page.tsx+++ b/ui/litellm-dashboard/src/app/page.tsx@@ -12,6 +12,7 @@ import ModelDashboard from "@/components/model_dashboard";import ViewUserDashboard from "@/components/view_users";import Teams from "@/components/teams";import Organizations from "@/components/organizations";+import { fetchOrganizations } from "@/components/organizations";import AdminPanel from "@/components/admins";import Settings from "@/components/settings";import GeneralSettings from "@/components/general_settings";@@ -28,7 +29,7 @@ import { setGlobalLitellmHeaderName } from "@/components/networking";import { Organization } from "@/components/networking";import GuardrailsPanel from "@/components/guardrails";import { fetchUserModels } from "@/components/create_key_button";-+import { fetchTeams } from "@/components/common_components/fetch_teams";function getCookie(name: string) {const cookieValue = document.cookie.split("; ")@@ -81,7 +82,6 @@ export default function CreateKeyPage() {const [userEmail, setUserEmail] = useState<null | string>(null);const [teams, setTeams] = useState<Team[] | null>(null);const [keys, setKeys] = useState<null | any[]>(null);- const [currentOrg, setCurrentOrg] = useState<Organization>(defaultOrg);const [organizations, setOrganizations] = useState<Organization[]>([]);const [userModels, setUserModels] = useState<string[]>([]);const [proxySettings, setProxySettings] = useState<ProxySettings>({@@ -179,22 +179,14 @@ export default function CreateKeyPage() {if (accessToken && userID && userRole) {fetchUserModels(userID, userRole, accessToken, setUserModels);}+ if (accessToken && userID && userRole) {+ fetchTeams(accessToken, userID, userRole, null, setTeams);+ }+ if (accessToken) {+ fetchOrganizations(accessToken, setOrganizations);+ }}, [accessToken, userID, userRole]);- const handleOrgChange = (org: Organization) => {- setCurrentOrg(org);- console.log(`org: ${JSON.stringify(org)}`)- if (org.members && userRole != "Admin") { // don't change user role if user is admin- for (const member of org.members) {- console.log(`member: ${JSON.stringify(member)}`)- if (member.user_id == userID) {- console.log(`member.user_role: ${member.user_role}`)- setUserRole(formatUserRole(member.user_role));- }- }- }- setTeams(null);- }return (<Suspense fallback={<div>Loading...</div>}>@@ -211,21 +203,16 @@ export default function CreateKeyPage() {setUserEmail={setUserEmail}setTeams={setTeams}setKeys={setKeys}- setOrganizations={setOrganizations}- currentOrg={currentOrg}+ organizations={organizations}/>) : (<div className="flex flex-col min-h-screen"><NavbaruserID={userID}userRole={userRole}- userEmail={userEmail}premiumUser={premiumUser}setProxySettings={setProxySettings}proxySettings={proxySettings}- currentOrg={currentOrg}- organizations={organizations}- onOrgChange={handleOrgChange}/><div className="flex flex-1 overflow-auto"><div className="mt-8">@@ -248,8 +235,7 @@ export default function CreateKeyPage() {setUserEmail={setUserEmail}setTeams={setTeams}setKeys={setKeys}- setOrganizations={setOrganizations}- currentOrg={currentOrg}+ organizations={organizations}/>) : page == "models" ? (<ModelDashboard@@ -288,7 +274,7 @@ export default function CreateKeyPage() {accessToken={accessToken}userID={userID}userRole={userRole}- currentOrg={currentOrg}+ organizations={organizations}/>) : page == "organizations" ? (<Organizationsdiff --git a/ui/litellm-dashboard/src/components/all_keys_table.tsx b/ui/litellm-dashboard/src/components/all_keys_table.tsxindex 6e3a491886e..4ed2886745a 100644--- a/ui/litellm-dashboard/src/components/all_keys_table.tsx+++ b/ui/litellm-dashboard/src/components/all_keys_table.tsx@@ -7,7 +7,8 @@ import { Button } from "@tremor/react"import KeyInfoView from "./key_info_view";import { Tooltip } from "antd";import { Team, KeyResponse } from "./key_team_helpers/key_list";-+import FilterComponent from "./common_components/filter";+import { Organization } from "./networking";interface AllKeysTableProps {keys: KeyResponse[];isLoading?: boolean;@@ -24,75 +25,12 @@ interface AllKeysTableProps {accessToken: string | null;userID: string | null;userRole: string | null;+ organizations: Organization[] | null;+ setCurrentOrg: React.Dispatch<React.SetStateAction<Organization | null>>;}// Define columns similar to our logs table-function KeyViewer({ row }: { row: Row<KeyResponse> }) {- return (- <div className="p-4 bg-gray-50">- <div className="bg-white rounded-lg shadow p-4">- <h3 className="text-lg font-medium">Key Details</h3>- <div className="mt-2 space-y-1">- <p>- <strong>Key Alias:</strong> {row.original.key_alias || "Not Set"}- </p>- <p>- <strong>Secret Key:</strong> {row.original.key_name}- </p>- <p>- <strong>Created:</strong>{" "}- {new Date(row.original.created_at).toLocaleString()}- </p>- <p>- <strong>Expires:</strong>{" "}- {row.original.expires- ? new Date(row.original.expires).toLocaleString()- : "Never"}- </p>- <p>- <strong>Spend:</strong> {Number(row.original.spend).toFixed(4)}- </p>- <p>- <strong>Budget:</strong>{" "}- {row.original.max_budget !== null- ? row.original.max_budget- : "Unlimited"}- </p>- <p>- <strong>Budget Reset:</strong>{" "}- {row.original.budget_reset_at- ? new Date(row.original.budget_reset_at).toLocaleString()- : "Never"}- </p>- <p>- <strong>Models:</strong>{" "}- {row.original.models && row.original.models.length > 0- ? row.original.models.join(", ")- : "-"}- </p>- <p>- <strong>Rate Limits:</strong> TPM:{" "}- {row.original.tpm_limit !== null- ? row.original.tpm_limit- : "Unlimited"}- , RPM:{" "}- {row.original.rpm_limit !== null- ? row.original.rpm_limit- : "Unlimited"}- </p>- <p>- <strong>Metadata:</strong>- </p>- <pre className="bg-gray-100 p-2 rounded text-xs overflow-auto">- {JSON.stringify(row.original.metadata, null, 2)}- </pre>- </div>- </div>- </div>- );-}-const TeamFilter = ({teams,selectedTeam,@@ -146,9 +84,55 @@ export function AllKeysTable({setSelectedTeam,accessToken,userID,- userRole+ userRole,+ organizations,+ setCurrentOrg}: AllKeysTableProps) {const [selectedKeyId, setSelectedKeyId] = useState<string | null>(null);+ const [filters, setFilters] = useState<{+ 'Team ID': string;+ 'Organization ID': string;+ }>({+ 'Team ID': '',+ 'Organization ID': ''+ });++ const handleFilterChange = (newFilters: Record<string, string>) => {+ // Update filters state+ setFilters({+ 'Team ID': newFilters['Team ID'] || '',+ 'Organization ID': newFilters['Organization ID'] || ''+ });++ // Handle Team change+ if (newFilters['Team ID']) {+ const selectedTeamData = teams?.find(team => team.team_id === newFilters['Team ID']);+ if (selectedTeamData) {+ setSelectedTeam(selectedTeamData);+ }+ }++ // Handle Org change+ if (newFilters['Organization ID']) {+ const selectedOrg = organizations?.find(org => org.organization_id === newFilters['Organization ID']);+ if (selectedOrg) {+ setCurrentOrg(selectedOrg);+ }+ }+ };++ const handleFilterReset = () => {+ // Reset filters state+ setFilters({+ 'Team ID': '',+ 'Organization ID': ''+ });++ // Reset team and org selections+ setSelectedTeam(null); // or whatever your default value should be+ setCurrentOrg(null); // or whatever your default value should be+ };+const columns: ColumnDef<KeyResponse>[] = [{@@ -183,9 +167,9 @@ export function AllKeysTable({),},{- header: "Organization",- accessorKey: "organization_id",- cell: (info) => info.getValue() ? info.renderValue() : "Not Set",+ header: "Secret Key",+ accessorKey: "key_name",+ cell: (info) => <span className="font-mono text-xs">{info.getValue() as string}</span>,},{header: "Team ID",@@ -198,9 +182,9 @@ export function AllKeysTable({cell: (info) => info.getValue() ? info.renderValue() : "Not Set",},{- header: "Secret Key",- accessorKey: "key_name",- cell: (info) => <span className="font-mono text-xs">{info.getValue() as string}</span>,+ header: "Organization ID",+ accessorKey: "organization_id",+ cell: (info) => info.getValue() ? info.renderValue() : "Not Set",},{header: "Created",@@ -275,6 +259,12 @@ export function AllKeysTable({},},];++ const filterOptions = [+ { name: 'Team ID', label: 'Team ID' },+ { name: 'Organization ID', label: 'Organization ID' }+ ];+return (<div className="w-full h-full overflow-hidden">@@ -290,12 +280,8 @@ export function AllKeysTable({/>) : (<div className="border-b py-4 flex-1 overflow-hidden">- <div className="flex items-center justify-between w-full">- <TeamFilter- teams={teams}- selectedTeam={selectedTeam}- setSelectedTeam={setSelectedTeam}- />+ <div className="flex items-center justify-between w-full mb-2">+ <FilterComponent options={filterOptions} onApplyFilters={handleFilterChange} initialValues={filters} onResetFilters={handleFilterReset}/><div className="flex items-center gap-4"><span className="inline-flex text-sm text-gray-700">Showing {isLoading ? "..." : `${(pagination.currentPage - 1) * pageSize + 1} - ${Math.min(pagination.currentPage * pageSize, pagination.totalCount)}`} of {isLoading ? "..." : pagination.totalCount} results@@ -325,6 +311,7 @@ export function AllKeysTable({</div></div><div className="h-[32rem] overflow-auto">+<DataTablecolumns={columns.filter(col => col.id !== 'expander')}data={keys}diff --git a/ui/litellm-dashboard/src/components/common_components/fetch_teams.tsx b/ui/litellm-dashboard/src/components/common_components/fetch_teams.tsxindex 6bc6ab6b0d6..6317a95af39 100644--- a/ui/litellm-dashboard/src/components/common_components/fetch_teams.tsx+++ b/ui/litellm-dashboard/src/components/common_components/fetch_teams.tsx@@ -3,9 +3,9 @@ import { teamListCall, DEFAULT_ORGANIZATION, Organization } from "../networking"export const fetchTeams = async (accessToken: string, userID: string | null, userRole: string | null, currentOrg: Organization | null, setTeams: (teams: any[]) => void) => {let givenTeams;if (userRole != "Admin" && userRole != "Admin Viewer") {- givenTeams = await teamListCall(accessToken, currentOrg?.organization_id || DEFAULT_ORGANIZATION, userID)+ givenTeams = await teamListCall(accessToken, currentOrg?.organization_id || null, userID)} else {- givenTeams = await teamListCall(accessToken, currentOrg?.organization_id || DEFAULT_ORGANIZATION)+ givenTeams = await teamListCall(accessToken, currentOrg?.organization_id || null)}console.log(`givenTeams: ${givenTeams}`)diff --git a/ui/litellm-dashboard/src/components/common_components/filter.tsx b/ui/litellm-dashboard/src/components/common_components/filter.tsxnew file mode 100644index 00000000000..38f7ed6b760--- /dev/null+++ b/ui/litellm-dashboard/src/components/common_components/filter.tsx@@ -0,0 +1,171 @@+import React, { useState, useRef, useEffect } from 'react';+import { Button, Input, Dropdown, MenuProps } from 'antd';+import { Card } from '@tremor/react';+import {+ FilterIcon,+ XIcon,+ CheckIcon,+ ChevronDownIcon,+ ChevronUpIcon+} from '@heroicons/react/outline';++interface FilterOption {+ name: string;+ label?: string;+}++interface FilterValues {+ [key: string]: string;+}++interface FilterComponentProps {+ options: FilterOption[];+ onApplyFilters: (filters: FilterValues) => void;+ initialValues?: FilterValues;+ buttonLabel?: string;+ onResetFilters: () => void;+}++const FilterComponent: React.FC<FilterComponentProps> = ({+ options,+ onApplyFilters,+ onResetFilters,+ initialValues = {},+ buttonLabel = "Filter",+}) => {+ const [showFilters, setShowFilters] = useState<boolean>(false);+ const [selectedFilter, setSelectedFilter] = useState<string>(options[0]?.name || '');+ const [filterValues, setFilterValues] = useState<FilterValues>(initialValues);+ const [tempValues, setTempValues] = useState<FilterValues>(initialValues);+ const [dropdownOpen, setDropdownOpen] = useState<boolean>(false);++ const filtersRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ const handleClickOutside = (event: MouseEvent) => {+ const target = event.target as HTMLElement;+ if (filtersRef.current &&+ !filtersRef.current.contains(target) &&+ !target.closest('.ant-dropdown')) {+ setShowFilters(false);+ }+ };++ document.addEventListener('mousedown', handleClickOutside);+ return () => document.removeEventListener('mousedown', handleClickOutside);+ }, []);++ const handleFilterChange = (value: string) => {+ setTempValues(prev => ({+ ...prev,+ [selectedFilter]: value+ }));+ };++ const clearFilters = () => {+ const emptyValues: FilterValues = {};+ options.forEach(option => {+ emptyValues[option.name] = '';+ });+ setTempValues(emptyValues);+ };++ const handleApplyFilters = () => {+ setFilterValues(tempValues);+ onApplyFilters(tempValues);+ setShowFilters(false);+ };++ const dropdownItems: MenuProps['items'] = options.map(option => ({+ key: option.name,+ label: (+ <div className="flex items-center gap-2">+ {selectedFilter === option.name && (+ <CheckIcon className="h-4 w-4 text-blue-600" />+ )}+ {option.label || option.name}+ </div>+ ),+ }));++ return (+ <div className="relative" ref={filtersRef}>+ <Button+ icon={<FilterIcon className="h-4 w-4" />}+ onClick={() => setShowFilters(!showFilters)}+ >+ {buttonLabel}+ </Button>++ {showFilters && (+ <Card className="absolute left-0 mt-2 w-96 z-50">+ <div className="flex flex-col gap-4">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">Where</span>++ <Dropdown+ menu={{+ items: dropdownItems,+ onClick: ({ key }) => {+ setSelectedFilter(key);+ setDropdownOpen(false);+ }+ }}+ onOpenChange={setDropdownOpen}+ open={dropdownOpen}+ trigger={['click']}+ >+ <Button className="min-w-32 text-left flex justify-between items-center">+ {selectedFilter}+ {dropdownOpen ? (+ <ChevronUpIcon className="h-4 w-4" />+ ) : (+ <ChevronDownIcon className="h-4 w-4" />+ )}+ </Button>+ </Dropdown>++ <Input+ placeholder="Enter value..."+ value={tempValues[selectedFilter] || ''}+ onChange={(e) => handleFilterChange(e.target.value)}+ suffix={+ tempValues[selectedFilter] ? (+ <XIcon+ className="h-4 w-4 cursor-pointer text-gray-400 hover:text-gray-500"+ onClick={(e) => {+ e.stopPropagation();+ handleFilterChange('');+ }}+ />+ ) : null+ }+ />+ </div>++ <div className="flex justify-end gap-2">+ <Button+ onClick={() => {+ clearFilters();+ const emptyValues: FilterValues = {};+ options.forEach(option => {+ emptyValues[option.name] = '';+ });+ onResetFilters();+ setShowFilters(false);+ }}+ >+ Cancel+ </Button>+ <Button type="primary" onClick={handleApplyFilters}>+ Apply Filters+ </Button>+ </div>+ </div>+ </Card>+ )}+ </div>+ );+};++export default FilterComponent;\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/key_team_helpers/key_list.tsx b/ui/litellm-dashboard/src/components/key_team_helpers/key_list.tsxindex 946f4d39509..fd9d1ef2452 100644--- a/ui/litellm-dashboard/src/components/key_team_helpers/key_list.tsx+++ b/ui/litellm-dashboard/src/components/key_team_helpers/key_list.tsx@@ -121,8 +121,7 @@ const useKeyList = ({const fetchKeys = async (params: Record<string, unknown> = {}): Promise<void> => {try {console.log("calling fetchKeys");- if (!currentOrg || !accessToken) {- console.log("currentOrg", currentOrg);+ if (!accessToken) {console.log("accessToken", accessToken);return;}@@ -130,7 +129,7 @@ const useKeyList = ({const data = await keyListCall(accessToken,- currentOrg.organization_id,+ currentOrg?.organization_id || null,selectedTeam?.team_id || "",params.page as number || 1,50diff --git a/ui/litellm-dashboard/src/components/navbar.tsx b/ui/litellm-dashboard/src/components/navbar.tsxindex e02706ec437..7319cb73068 100644--- a/ui/litellm-dashboard/src/components/navbar.tsx+++ b/ui/litellm-dashboard/src/components/navbar.tsx@@ -7,30 +7,17 @@ import { defaultOrg } from "@/components/common_components/default_org";interface NavbarProps {userID: string | null;userRole: string | null;- userEmail: string | null;premiumUser: boolean;setProxySettings: React.Dispatch<React.SetStateAction<any>>;proxySettings: any;- currentOrg: Organization | null;- onOrgChange?: (org: Organization) => void;- onNewOrg?: () => void;- organizations?: Organization[];}const Navbar: React.FC<NavbarProps> = ({userID,userRole,- userEmail,premiumUser,- setProxySettings,proxySettings,- currentOrg = null,- onOrgChange = () => {},- onNewOrg = () => {},- organizations = []}) => {- console.log(`currentOrg: ${JSON.stringify(currentOrg)}`)- console.log(`organizations: ${JSON.stringify(organizations)}`)const isLocal = process.env.NODE_ENV === "development";const imageUrl = isLocal ? "http://localhost:4000/get_image" : "/get_image";let logoutUrl = proxySettings?.PROXY_LOGOUT_URL || "";@@ -57,44 +44,6 @@ const Navbar: React.FC<NavbarProps> = ({}];- const orgMenuItems: MenuProps["items"] = [- {- key: 'header',- label: 'Organizations',- type: 'group' as const,- style: {- color: '#6B7280',- fontSize: '0.875rem'- }- },- {- key: "default",- label: (- <div className="flex items-center justify-between py-1">- <span className="text-sm">Default Organization</span>- </div>- ),- onClick: () => onOrgChange(defaultOrg)- },- ...organizations.filter(org => org.organization_id !== null).map(org => ({- key: org.organization_id ?? "default",- label: (- <div className="flex items-center justify-between py-1">- <span className="text-sm">{org.organization_alias}</span>- </div>- ),- onClick: () => onOrgChange(org)- })),- {- key: "note",- label: (- <div className="flex items-center justify-between py-1 px-2 bg-gray-50 text-gray-500 text-xs italic">- <span>Switching between organizations on the UI is currently in beta.</span>- </div>- ),- disabled: true- }- ];return (<nav className="bg-white border-b border-gray-200 sticky top-0 z-10">@@ -111,35 +60,6 @@ const Navbar: React.FC<NavbarProps> = ({</Link></div>- {/* Organization selector with beta label */}- <div className="ml-8 flex items-center">- <Dropdown- menu={{- items: orgMenuItems,- style: {- width: '280px',- padding: '4px',- marginTop: '4px'- }- }}- trigger={['click']}- placement="bottomLeft"- >- <button className="inline-flex items-center text-[13px] text-gray-700 hover:text-gray-900 transition-colors">- {currentOrg ? currentOrg.organization_alias : "Default Organization"}- <svg- className="ml-1 w-4 h-4 text-gray-500"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- >- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 9l-7 7-7-7" />- </svg>- </button>- </Dropdown>- <span className="ml-2 text-[10px] bg-blue-100 text-blue-800 font-medium px-2 py-0.5 rounded">BETA</span>- </div>-{/* Right side nav items */}<div className="flex items-center space-x-5 ml-auto"><adiff --git a/ui/litellm-dashboard/src/components/organizations.tsx b/ui/litellm-dashboard/src/components/organizations.tsxindex 5e6cf6f58e4..3e1cd3aed41 100644--- a/ui/litellm-dashboard/src/components/organizations.tsx+++ b/ui/litellm-dashboard/src/components/organizations.tsx@@ -40,7 +40,7 @@ interface OrganizationsTableProps {premiumUser: boolean;}-const fetchOrganizations = async (accessToken: string, setOrganizations: (organizations: Organization[]) => void) => {+export const fetchOrganizations = async (accessToken: string, setOrganizations: (organizations: Organization[]) => void) => {const organizations = await organizationListCall(accessToken);setOrganizations(organizations);};diff --git a/ui/litellm-dashboard/src/components/teams.tsx b/ui/litellm-dashboard/src/components/teams.tsxindex 03879a11544..34a58fcd162 100644--- a/ui/litellm-dashboard/src/components/teams.tsx+++ b/ui/litellm-dashboard/src/components/teams.tsx@@ -22,7 +22,7 @@ import {message,Tooltip} from "antd";-import { fetchAvailableModelsForTeamOrKey, getModelDisplayName } 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 { getGuardrailsList } from "./networking";@@ -66,7 +66,7 @@ interface TeamProps {setTeams: React.Dispatch<React.SetStateAction<Team[] | null>>;userID: string | null;userRole: string | null;- currentOrg: Organization | null;+ organizations: Organization[] | null;}interface EditTeamModalProps {@@ -85,27 +85,38 @@ import {teamListCall} from "./networking";+const getOrganizationModels = (organization: Organization | null, userModels: string[]) => {+ let tempModelsToPick = [];-const Team: React.FC<TeamProps> = ({+ if (organization) {+ if (organization.models.length > 0) {+ console.log(`organization.models: ${organization.models}`);+ tempModelsToPick = organization.models;+ } else {+ // show all available models if the team has no models set+ tempModelsToPick = userModels;+ }+ } else {+ // no team set, show all available models+ tempModelsToPick = userModels;+ }++ return unfurlWildcardModelsInList(tempModelsToPick, userModels);+}++const Teams: React.FC<TeamProps> = ({teams,searchParams,accessToken,setTeams,userID,userRole,- currentOrg+ organizations}) => {const [lastRefreshed, setLastRefreshed] = useState("");-+ const [currentOrg, setCurrentOrg] = useState<Organization | null>(null);+ const [currentOrgForCreateTeam, setCurrentOrgForCreateTeam] = useState<Organization | null>(null);- useEffect(() => {- console.log(`inside useeffect - ${teams}`)- if (teams === null && accessToken) {- // Call your function here- fetchTeams(accessToken, userID, userRole, currentOrg, setTeams)- }- }, [teams]);-useEffect(() => {console.log(`inside useeffect - ${lastRefreshed}`)if (accessToken) {@@ -133,6 +144,7 @@ const Team: React.FC<TeamProps> = ({const [userModels, setUserModels] = useState<string[]>([]);const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);const [teamToDelete, setTeamToDelete] = useState<string | null>(null);+ const [modelsToPick, setModelsToPick] = useState<string[]>([]);@@ -141,6 +153,14 @@ const Team: React.FC<TeamProps> = ({// Add this state near the other useState declarationsconst [guardrailsList, setGuardrailsList] = useState<string[]>([]);+ useEffect(() => {+ console.log(`currentOrgForCreateTeam: ${currentOrgForCreateTeam}`);+ const models = getOrganizationModels(currentOrgForCreateTeam, userModels);+ console.log(`models: ${models}`);+ setModelsToPick(models);+ form.setFieldValue('models', []);+ }, [currentOrgForCreateTeam, userModels]);+// Add this useEffect to fetch guardrailsuseEffect(() => {const fetchGuardrails = async () => {@@ -200,10 +220,7 @@ const Team: React.FC<TeamProps> = ({try {await teamDeleteCall(accessToken, teamToDelete);// Successfully completed the deletion. Update the state to trigger a rerender.- const filteredData = teams.filter(- (item) => item.team_id !== teamToDelete- );- setTeams(filteredData);+ 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.@@ -235,41 +252,7 @@ const Team: React.FC<TeamProps> = ({}};- const fetchTeamInfo = async () => {- try {- if (userID === null || userRole === null || accessToken === null) {- return;- }-- if (teams === null) {- return;- }-- let _team_id_to_info: Record<string, any> = {};- let teamList;- if (userRole != "Admin" && userRole != "Admin Viewer") {- teamList = await teamListCall(accessToken, currentOrg?.organization_id || DEFAULT_ORGANIZATION, userID)- } else {- teamList = await teamListCall(accessToken, currentOrg?.organization_id || DEFAULT_ORGANIZATION)- }-- for (let i = 0; i < teamList.length; i++) {- let team = teamList[i];- let _team_id = team.team_id;-- // Use the team info directly from the teamList- if (team !== null) {- _team_id_to_info = { ..._team_id_to_info, [_team_id]: team };- }- }- setPerTeamInfo(_team_id_to_info);- } catch (error) {- console.error("Error fetching team info:", error);- }- };-fetchUserModels();- fetchTeamInfo();}, [accessToken, userID, userRole, teams]);const handleCreate = async (formValues: Record<string, any>) => {@@ -339,7 +322,7 @@ const Team: React.FC<TeamProps> = ({return (- <div className="w-full mx-4">+ <div className="w-full mx-4 h-[75vh]">{selectedTeamId ? (<TeamInfoViewteamId={selectedTeamId}@@ -378,7 +361,7 @@ const Team: React.FC<TeamProps> = ({</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]">+ <Card className="w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]"><Table><TableHead><TableRow>@@ -388,7 +371,7 @@ const Team: React.FC<TeamProps> = ({<TableHeaderCell>Spend (USD)</TableHeaderCell><TableHeaderCell>Budget (USD)</TableHeaderCell><TableHeaderCell>Models</TableHeaderCell>- <TableHeaderCell>TPM / RPM Limits</TableHeaderCell>+ <TableHeaderCell>Organization</TableHeaderCell><TableHeaderCell>Info</TableHeaderCell></TableRow></TableHead>@@ -396,10 +379,10 @@ const Team: React.FC<TeamProps> = ({<TableBody>{teams && teams.length > 0? teams- .filter((team) => {- const targetOrgId = currentOrg ? currentOrg.organization_id : null;- return team.organization_id === targetOrgId;- })+ .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}>@@ -510,18 +493,8 @@ const Team: React.FC<TeamProps> = ({) : null}</TableCell>- <TableCell- style={{- maxWidth: "4px",- whiteSpace: "pre-wrap",- overflow: "hidden",- }}- >- <Text>- TPM: {team.tpm_limit ? team.tpm_limit : "Unlimited"}{" "}- <br></br>RPM:{" "}- {team.rpm_limit ? team.rpm_limit : "Unlimited"}- </Text>+ <TableCell>+ {team.organization_id}</TableCell><TableCell><Text>@@ -648,7 +621,42 @@ const Team: React.FC<TeamProps> = ({><TextInput placeholder="" /></Form.Item>- <Form.Item label="Models" name="models">+ <Form.Item+ label="Organization"+ name="organization_id"+ initialValue={currentOrg ? currentOrg.organization_id : null}+ className="mt-8"+ >+ <Select2+ showSearch+ placeholder="Search or select a team"+ 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 organization has access to">+ <InfoCircleOutlined style={{ marginLeft: '4px' }} />+ </Tooltip>+ </span>+ } name="models"><Select2mode="multiple"placeholder="Select models"@@ -660,7 +668,7 @@ const Team: React.FC<TeamProps> = ({>All Proxy Models</Select2.Option>- {userModels.map((model) => (+ {modelsToPick.map((model) => (<Select2.Option key={model} value={model}>{getModelDisplayName(model)}</Select2.Option>@@ -710,18 +718,6 @@ const Team: React.FC<TeamProps> = ({}}/></Form.Item>- <Form.Item- label="Organization ID"- name="organization_id"- help="Assign team to an organization. Found in the 'Organization' tab."- >- <TextInput- placeholder=""- onChange={(e) => {- e.target.value = e.target.value.trim();- }}- />- </Form.Item><Form.Itemlabel={<span>@@ -774,4 +770,4 @@ const Team: React.FC<TeamProps> = ({);};-export default Team;+export default Teams;diff --git a/ui/litellm-dashboard/src/components/user_dashboard.tsx b/ui/litellm-dashboard/src/components/user_dashboard.tsxindex 1077ae11ea4..8b9f5e328f0 100644--- a/ui/litellm-dashboard/src/components/user_dashboard.tsx+++ b/ui/litellm-dashboard/src/components/user_dashboard.tsx@@ -5,7 +5,6 @@ import {modelAvailableCall,getTotalSpendCall,getProxyUISettings,- teamListCall,Organization,organizationListCall,DEFAULT_ORGANIZATION@@ -63,9 +62,8 @@ interface UserDashboardProps {setUserEmail: React.Dispatch<React.SetStateAction<string | null>>;setTeams: React.Dispatch<React.SetStateAction<Team[] | null>>;setKeys: React.Dispatch<React.SetStateAction<Object[] | null>>;- setOrganizations: React.Dispatch<React.SetStateAction<Organization[]>>;premiumUser: boolean;- currentOrg: Organization | null;+ organizations: Organization[] | null;}type TeamInterface = {@@ -84,14 +82,13 @@ const UserDashboard: React.FC<UserDashboardProps> = ({setUserEmail,setTeams,setKeys,- setOrganizations,premiumUser,- currentOrg+ organizations}) => {- console.log(`currentOrg in user dashboard: ${JSON.stringify(currentOrg)}`)const [userSpendData, setUserSpendData] = useState<UserInfo | null>(null);+ const [currentOrg, setCurrentOrg] = useState<Organization | null>(null);// Assuming useSearchParams() hook exists and works in your setupconst searchParams = useSearchParams()!;@@ -244,13 +241,8 @@ const UserDashboard: React.FC<UserDashboardProps> = ({// Optionally, update your UI to reflect the error state here as well}};- const fetchOrganizations = async () => {- const organizations = await organizationListCall(accessToken);- setOrganizations(organizations);- }fetchData();fetchTeams(accessToken, userID, userRole, currentOrg, setTeams);- fetchOrganizations();}}}, [userID, token, accessToken, keys, userRole]);@@ -360,6 +352,8 @@ const UserDashboard: React.FC<UserDashboardProps> = ({premiumUser={premiumUser}teams={teams}currentOrg={currentOrg}+ setCurrentOrg={setCurrentOrg}+ organizations={organizations}/></Col></Grid>diff --git a/ui/litellm-dashboard/src/components/view_key_table.tsx b/ui/litellm-dashboard/src/components/view_key_table.tsxindex 005a08c5f55..8aadbc8438f 100644--- a/ui/litellm-dashboard/src/components/view_key_table.tsx+++ b/ui/litellm-dashboard/src/components/view_key_table.tsx@@ -105,6 +105,8 @@ interface ViewKeyTableProps {teams: Team[] | null;premiumUser: boolean;currentOrg: Organization | null;+ organizations: Organization[] | null;+ setCurrentOrg: React.Dispatch<React.SetStateAction<Organization | null>>;}interface ItemData {@@ -150,7 +152,9 @@ const ViewKeyTable: React.FC<ViewKeyTableProps> = ({setData,teams,premiumUser,- currentOrg+ currentOrg,+ organizations,+ setCurrentOrg}) => {const [isButtonClicked, setIsButtonClicked] = useState(false);const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);@@ -170,22 +174,6 @@ const ViewKeyTable: React.FC<ViewKeyTableProps> = ({}, [selectedTeam]);// Build a memoized filters object for the backend call.- const filters = useMemo(- () => {- const f: { team_id?: string; key_alias?: string } = {};-- if (teamFilter) {- f.team_id = teamFilter;- }-- if (keyAliasFilter) {- f.key_alias = keyAliasFilter;- }-- return f;- },- [teamFilter, keyAliasFilter]- );// Pass filters into the hook so the API call includes these query parameters.const { keys, isLoading, error, pagination, refresh } = useKeyList({@@ -330,330 +318,6 @@ const ViewKeyTable: React.FC<ViewKeyTableProps> = ({}}, [teams]);-- const ModelLimitModal: React.FC<ModelLimitModalProps> = ({- visible,- onCancel,- token,- onSubmit,- accessToken,- }) => {- const [modelLimits, setModelLimits] = useState<{- [key: string]: { tpm: number; rpm: number };- }>({});- const [availableModels, setAvailableModels] = useState<string[]>([]);- const [newModelRow, setNewModelRow] = useState<string | null>(null);-- useEffect(() => {- if (token.metadata) {- const tpmLimits = token.metadata.model_tpm_limit || {};- const rpmLimits = token.metadata.model_rpm_limit || {};- const combinedLimits: CombinedLimits = {};-- Object.keys({ ...tpmLimits, ...rpmLimits }).forEach((model) => {- combinedLimits[model] = {- tpm: (tpmLimits as ModelLimits)[model] || 0,- rpm: (rpmLimits as ModelLimits)[model] || 0,- };- });-- setModelLimits(combinedLimits);- }-- const fetchAvailableModels = async () => {- try {- const modelDataResponse = await modelInfoCall(accessToken, "", "");- const allModelGroups: string[] = Array.from(- new Set(- modelDataResponse.data.map((model: any) => model.model_name)- )- );- setAvailableModels(allModelGroups);- } catch (error) {- console.error("Error fetching model data:", error);- message.error("Failed to fetch available models");- }- };-- fetchAvailableModels();- }, [token, accessToken]);-- const handleLimitChange = (- model: string,- type: "tpm" | "rpm",- value: number | null- ) => {- setModelLimits((prev) => ({- ...prev,- [model]: {- ...prev[model],- [type]: value || 0,- },- }));- };-- const handleAddLimit = () => {- setNewModelRow("");- };-- const handleModelSelect = (model: string) => {- if (!modelLimits[model]) {- setModelLimits((prev) => ({- ...prev,- [model]: { tpm: 0, rpm: 0 },- }));- }- setNewModelRow(null);- };-- const handleRemoveModel = (model: string) => {- setModelLimits((prev) => {- const { [model]: _, ...rest } = prev;- return rest;- });- };-- const handleSubmit = () => {- const updatedMetadata = {- ...token.metadata,- model_tpm_limit: Object.fromEntries(- Object.entries(modelLimits).map(([model, limits]) => [- model,- limits.tpm,- ])- ),- model_rpm_limit: Object.fromEntries(- Object.entries(modelLimits).map(([model, limits]) => [- model,- limits.rpm,- ])- ),- };- onSubmit(updatedMetadata);- };-- return (- <Modal- title="Edit Model-Specific Limits"- visible={visible}- onCancel={onCancel}- footer={null}- width={800}- >- <div className="space-y-4">- <Table>- <TableHead>- <TableRow>- <TableHeaderCell>Model</TableHeaderCell>- <TableHeaderCell>TPM Limit</TableHeaderCell>- <TableHeaderCell>RPM Limit</TableHeaderCell>- <TableHeaderCell>Actions</TableHeaderCell>- </TableRow>- </TableHead>- <TableBody>- {Object.entries(modelLimits).map(([model, limits]) => (- <TableRow key={model}>- <TableCell>{model}</TableCell>- <TableCell>- <InputNumber- value={limits.tpm}- onChange={(value) =>- handleLimitChange(model, "tpm", value)- }- />- </TableCell>- <TableCell>- <InputNumber- value={limits.rpm}- onChange={(value) =>- handleLimitChange(model, "rpm", value)- }- />- </TableCell>- <TableCell>- <Button onClick={() => handleRemoveModel(model)}>- Remove- </Button>- </TableCell>- </TableRow>- ))}- {newModelRow !== null && (- <TableRow>- <TableCell>- <Select2- style={{ width: 200 }}- placeholder="Select a model"- onChange={handleModelSelect}- value={newModelRow || undefined}- >- {availableModels- .filter((m) => !modelLimits.hasOwnProperty(m))- .map((m) => (- <Select2.Option key={m} value={m}>- {m}- </Select2.Option>- ))}- </Select2>- </TableCell>- <TableCell>-</TableCell>- <TableCell>-</TableCell>- <TableCell>- <Button onClick={() => setNewModelRow(null)}>Cancel</Button>- </TableCell>- </TableRow>- )}- </TableBody>- </Table>- <Button onClick={handleAddLimit} disabled={newModelRow !== null}>- Add Limit- </Button>- </div>- <div className="flex justify-end space-x-4 mt-6">- <Button onClick={onCancel}>Cancel</Button>- <Button onClick={handleSubmit}>Save</Button>- </div>- </Modal>- );- };-- const handleEditClick = (token: any) => {- console.log("handleEditClick:", token);-- // set token.token to token.token_id if token_id is not null- if (token.token == null) {- if (token.token_id !== null) {- token.token = token.token_id;- }- }-- // Convert the budget_duration to the corresponding select option- let budgetDuration = null;- if (token.budget_duration) {- switch (token.budget_duration) {- case "24h":- budgetDuration = "daily";- break;- case "7d":- budgetDuration = "weekly";- break;- case "30d":- budgetDuration = "monthly";- break;- default:- budgetDuration = "None";- }- }-- setSelectedToken({- ...token,- budget_duration: budgetDuration,- });-- //setSelectedToken(token);- setEditModalVisible(true);- };-- const handleEditCancel = () => {- setEditModalVisible(false);- setSelectedToken(null);- };-- const handleEditSubmit = async (formValues: Record<string, any>) => {- /**- * Call API to update team with teamId and values- *- * Client-side validation: For selected team, ensure models in team + max budget < team max budget- */- if (accessToken == null) {- return;- }-- const currentKey = formValues.token;- formValues.key = currentKey;-- // Convert metadata back to an object if it exists and is a string- if (formValues.metadata && typeof formValues.metadata === "string") {- try {- const parsedMetadata = JSON.parse(formValues.metadata);- // Only add guardrails if they are set in form values- formValues.metadata = {- ...parsedMetadata,- ...(formValues.guardrails?.length > 0 ?- { guardrails: formValues.guardrails }- : {}),- };- } catch (error) {- console.error("Error parsing metadata JSON:", error);- message.error(- "Invalid metadata JSON for formValue " + formValues.metadata- );- return;- }- } else {- // If metadata is not a string (or doesn't exist), only add guardrails if they are set- formValues.metadata = {- ...(formValues.metadata || {}),- ...(formValues.guardrails?.length > 0 ?- { guardrails: formValues.guardrails }- : {}),- };- }-- // Convert the budget_duration back to the API expected format- if (formValues.budget_duration) {- switch (formValues.budget_duration) {- case "daily":- formValues.budget_duration = "24h";- break;- case "weekly":- formValues.budget_duration = "7d";- break;- case "monthly":- formValues.budget_duration = "30d";- break;- }- }-- console.log("handleEditSubmit:", formValues);-- try {- let newKeyValues = await keyUpdateCall(accessToken, formValues);- console.log("handleEditSubmit: newKeyValues", newKeyValues);-- // Update the keys with the update key- if (data) {- const updatedData = data.map((key) =>- key.token === currentKey ? newKeyValues : key- );- setData(updatedData);- }- message.success("Key updated successfully");-- setEditModalVisible(false);- setSelectedToken(null);- } catch (error) {- console.error("Error updating key:", error);- message.error("Failed to update key");- }- };-- const handleDelete = async (token: any) => {- console.log("handleDelete:", token);- if (token.token == null) {- if (token.token_id !== null) {- token.token = token.token_id;- }- }- if (data == null) {- return;- }-- // Set the key to delete and open the confirmation modal- setKeyToDelete(token.token);- localStorage.removeItem("userData" + userID);- setIsDeleteModalOpen(true);- };-const confirmDelete = async () => {if (keyToDelete == null || data == null) {return;@@ -740,11 +404,6 @@ const ViewKeyTable: React.FC<ViewKeyTableProps> = ({}};- // New filter UI rendered above the table.- // For the team filter we use the teams prop, and for key alias we compute unique aliases from the keys.- const uniqueKeyAliases = Array.from(- new Set(keys.map((k) => (k.key_alias ? k.key_alias : "Not Set")))- );return (<div>@@ -760,6 +419,8 @@ const ViewKeyTable: React.FC<ViewKeyTableProps> = ({accessToken={accessToken}userID={userID}userRole={userRole}+ organizations={organizations}+ setCurrentOrg={setCurrentOrg}/>{isDeleteModalOpen && (