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
feat: Add logo customization for LiteLLM admin UI (#12958)
Cole McIntosh596592599a8e
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 0732f2eb454..78d8d29b99a 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -7772,6 +7772,13 @@ async def claim_onboarding_link(data: InvitationClaim):return user_obj[email protected]("/get_logo_url", include_in_schema=False)+def get_logo_url():+ """Get the current logo URL from environment"""+ logo_path = os.getenv("UI_LOGO_PATH", "")+ return {"logo_url": logo_path}++@app.get("/get_image", include_in_schema=False)def get_image():"""Get logo to show on admin UI"""diff --git a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.pyindex 8557bd2bafb..83acf0e8226 100644--- a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py+++ b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py@@ -1,7 +1,7 @@#### CRUD ENDPOINTS for UI Settings #####-from typing import Any, Dict, List, Union+from typing import Any, Dict, List, Union, Optional-from fastapi import APIRouter, Depends, HTTPException+from fastapi import APIRouter, Depends, HTTPException, UploadFile, Fileimport litellmfrom litellm._logging import verbose_proxy_logger@@ -19,6 +19,16 @@ class IPAddress(BaseModel):ip: str+class UIThemeConfig(BaseModel):+ """Configuration for UI theme customization"""++ # Logo configuration+ logo_url: Optional[str] = Field(+ default=None,+ description="URL or path to custom logo image. Can be a local file path or HTTP/HTTPS URL"+ )++class SettingsResponse(BaseModel):"""Base response model for settings with values and schema information"""@@ -47,6 +57,12 @@ class DefaultTeamSettingsResponse(SettingsResponse):pass+class UIThemeSettingsResponse(SettingsResponse):+ """Response model for UI theme settings"""++ pass++@router.get("/get/allowed_ips",tags=["Budget & Spend Tracking"],@@ -507,3 +523,155 @@ async def update_sso_settings(sso_config: SSOConfig):"status": "success","settings": sso_data,}+++ "/get/ui_theme_settings",+ tags=["UI Theme Settings"],+ dependencies=[Depends(user_api_key_auth)],+ response_model=UIThemeSettingsResponse,+)+async def get_ui_theme_settings():+ """+ Get UI theme configuration from the litellm_settings.+ Returns current logo settings for UI customization.+ """+ from litellm.proxy.proxy_server import proxy_config++ # Load existing config+ config = await proxy_config.get_config()++ return await _get_settings_with_schema(+ settings_key="ui_theme_config",+ settings_class=UIThemeConfig,+ config=config,+ )+++ "/update/ui_theme_settings",+ tags=["UI Theme Settings"],+ dependencies=[Depends(user_api_key_auth)],+)+async def update_ui_theme_settings(theme_config: UIThemeConfig):+ """+ Update UI theme configuration.+ Updates logo settings for the admin UI.+ """+ from litellm.proxy.proxy_server import proxy_config, store_model_in_db+ import os++ if store_model_in_db is not True:+ raise HTTPException(+ status_code=500,+ detail={+ "error": "Set `'STORE_MODEL_IN_DB='True'` in your env to enable this feature."+ },+ )++ # Load existing config+ config = await proxy_config.get_config()++ # Update config with UI theme settings+ if "general_settings" not in config:+ config["general_settings"] = {}++ if "environment_variables" not in config:+ config["environment_variables"] = {}++ # Convert theme config to dict+ theme_data = theme_config.model_dump(exclude_none=True)++ # Store UI theme config in litellm_settings (where it's retrieved from)+ if "litellm_settings" not in config:+ config["litellm_settings"] = {}+ config["litellm_settings"]["ui_theme_config"] = theme_data++ # Update UI_LOGO_PATH environment variable if logo_url is provided+ # If logo_url is empty string, None, or null, remove the environment variable to use default+ logo_url = theme_data.get("logo_url")+ verbose_proxy_logger.debug(f"Updating logo_url: {logo_url}")++ if logo_url and isinstance(logo_url, str) and logo_url.strip(): # Check if logo_url exists and is not empty/whitespace+ config["environment_variables"]["UI_LOGO_PATH"] = logo_url+ os.environ["UI_LOGO_PATH"] = logo_url+ verbose_proxy_logger.debug(f"Set UI_LOGO_PATH to: {logo_url}")+ else:+ # Remove the environment variable to restore default logo+ if "UI_LOGO_PATH" in config.get("environment_variables", {}):+ del config["environment_variables"]["UI_LOGO_PATH"]+ verbose_proxy_logger.debug("Removed UI_LOGO_PATH from config")+ if "UI_LOGO_PATH" in os.environ:+ del os.environ["UI_LOGO_PATH"]+ verbose_proxy_logger.debug("Removed UI_LOGO_PATH from environment")++ # Handle environment variable encryption if needed+ stored_config = config.copy()+ if "environment_variables" in stored_config and len(stored_config["environment_variables"]) > 0:+ # Only encrypt if there are environment variables to encrypt+ stored_config["environment_variables"] = proxy_config._encrypt_env_variables(+ environment_variables=stored_config["environment_variables"]+ )++ # Save the updated config+ await proxy_config.save_config(new_config=stored_config)++ return {+ "message": "Logo settings updated successfully.",+ "status": "success",+ "theme_config": theme_data,+ }+++ "/upload/logo",+ tags=["UI Theme Settings"],+ dependencies=[Depends(user_api_key_auth)],+)+async def upload_logo(file: UploadFile = File(...)):+ """+ Upload a custom logo for the admin UI.+ Accepts image files (PNG, JPG, JPEG, SVG) and stores them for use in the UI.+ """+ import os+ from pathlib import Path++ # Validate file type+ allowed_extensions = {".png", ".jpg", ".jpeg", ".svg"}+ file_extension = Path(file.filename or "").suffix.lower()++ if file_extension not in allowed_extensions:+ raise HTTPException(+ status_code=400,+ detail=f"Invalid file type. Allowed types: {', '.join(allowed_extensions)}"+ )++ # Validate file size (max 5MB)+ file_content = await file.read()+ if len(file_content) > 5 * 1024 * 1024: # 5MB+ raise HTTPException(+ status_code=400,+ detail="File size too large. Maximum size is 5MB."+ )++ # Create uploads directory if it doesn't exist+ current_dir = os.path.dirname(os.path.abspath(__file__))+ upload_dir = os.path.join(current_dir, "..", "uploads")+ os.makedirs(upload_dir, exist_ok=True)++ # Generate unique filename+ import uuid+ unique_filename = f"logo_{uuid.uuid4().hex}{file_extension}"+ file_path = os.path.join(upload_dir, unique_filename)++ # Save the file+ with open(file_path, "wb") as buffer:+ buffer.write(file_content)++ return {+ "message": "Logo uploaded successfully",+ "status": "success",+ "file_path": file_path,+ "filename": unique_filename,+ "file_size": len(file_content),+ }diff --git a/ui/litellm-dashboard/src/app/page.tsx b/ui/litellm-dashboard/src/app/page.tsxindex 2194bbaec48..7106a6f884f 100644--- a/ui/litellm-dashboard/src/app/page.tsx+++ b/ui/litellm-dashboard/src/app/page.tsx@@ -6,6 +6,7 @@ import { jwtDecode } from "jwt-decode";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { Team } from "@/components/key_team_helpers/key_list";import Navbar from "@/components/navbar";+import { ThemeProvider } from "@/contexts/ThemeContext";import UserDashboard from "@/components/user_dashboard";import ModelDashboard from "@/components/model_dashboard";import ViewUserDashboard from "@/components/view_users";@@ -39,6 +40,7 @@ import { fetchTeams } from "@/components/common_components/fetch_teams";import { MCPServers } from "@/components/mcp_tools";import TagManagement from "@/components/tag_management";import VectorStoreManagement from "@/components/vector_store_management";+import UIThemeSettings from "@/components/ui_theme_settings";import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";import { cx } from "@/lib/cva.config";@@ -232,8 +234,9 @@ export default function CreateKeyPage() {return (<Suspense fallback={<LoadingScreen />}><QueryClientProvider client={queryClient}>- {invitation_id ? (- <UserDashboard+ <ThemeProvider accessToken={accessToken}>+ {invitation_id ? (+ <UserDashboarduserID={userID}userRole={userRole}premiumUser={premiumUser}@@ -376,6 +379,12 @@ export default function CreateKeyPage() {accessToken={accessToken}modelData={modelData}/>+ ) : page == "ui-theme" ? (+ <UIThemeSettings+ userID={userID}+ userRole={userRole}+ accessToken={accessToken}+ />) : page == "model-hub-table" ? (<ModelHubTableaccessToken={accessToken}@@ -446,6 +455,7 @@ export default function CreateKeyPage() {</div></div>)}+ </ThemeProvider></QueryClientProvider></Suspense>);diff --git a/ui/litellm-dashboard/src/components/leftnav.tsx b/ui/litellm-dashboard/src/components/leftnav.tsxindex e7394525f48..0f7858968c0 100644--- a/ui/litellm-dashboard/src/components/leftnav.tsx+++ b/ui/litellm-dashboard/src/components/leftnav.tsx@@ -23,6 +23,7 @@ import {LockOutlined,ToolOutlined,TagsOutlined,+ BgColorsOutlined,} from '@ant-design/icons';import { old_admin_roles, v2_admin_role_names, all_admin_roles, rolesAllowedToSeeUsage, rolesWithWriteAccess, internalUserRoles, isAdminRole } from '../utils/roles';import UsageIndicator from './usage_indicator';@@ -106,6 +107,7 @@ const Sidebar: React.FC<SidebarProps> = ({{ key: "11", page: "general-settings", label: "Router Settings", icon: <SettingOutlined />, roles: all_admin_roles },{ key: "8", page: "settings", label: "Logging & Alerts", icon: <SettingOutlined />, roles: all_admin_roles },{ key: "13", page: "admin-panel", label: "Admin Settings", icon: <SettingOutlined />, roles: all_admin_roles },+ { key: "14", page: "ui-theme", label: "UI Theme", icon: <BgColorsOutlined />, roles: all_admin_roles },]}];diff --git a/ui/litellm-dashboard/src/components/navbar.tsx b/ui/litellm-dashboard/src/components/navbar.tsxindex dd43c80da1e..0b5a277b9cd 100644--- a/ui/litellm-dashboard/src/components/navbar.tsx+++ b/ui/litellm-dashboard/src/components/navbar.tsx@@ -1,9 +1,9 @@-import Link from "next/link";-import React, { useState, useEffect } from "react";-import type { MenuProps } from "antd";-import { Dropdown, Tooltip } from "antd";-import { getProxyBaseUrl, Organization } from "@/components/networking";-import { defaultOrg } from "@/components/common_components/default_org";+import Link from "next/link"+import React, { useState, useEffect } from "react"+import type { MenuProps } from "antd"+import { Dropdown, Tooltip } from "antd"+import { getProxyBaseUrl, Organization } from "@/components/networking"+import { defaultOrg } from "@/components/common_components/default_org"import {UserOutlined,LogoutOutlined,@@ -12,9 +12,10 @@ import {CrownOutlined,MailOutlined,SafetyOutlined-} from '@ant-design/icons';-import { clearTokenCookies } from "@/utils/cookieUtils";-import { fetchProxySettings } from "@/utils/proxyUtils";+} from '@ant-design/icons'+import { clearTokenCookies } from "@/utils/cookieUtils"+import { fetchProxySettings } from "@/utils/proxyUtils"+import { useTheme } from "@/contexts/ThemeContext"interface NavbarProps {userID: string | null;@@ -38,8 +39,11 @@ const Navbar: React.FC<NavbarProps> = ({isPublicPage = false,}) => {const baseUrl = getProxyBaseUrl();- const imageUrl = baseUrl + "/get_image";const [logoutUrl, setLogoutUrl] = useState("");+ const { logoUrl } = useTheme();++ // Simple logo URL: use custom logo if available, otherwise default+ const imageUrl = logoUrl || `${baseUrl}/get_image`;useEffect(() => {const initializeProxySettings = async () => {diff --git a/ui/litellm-dashboard/src/components/ui_theme_settings.tsx b/ui/litellm-dashboard/src/components/ui_theme_settings.tsxnew file mode 100644index 00000000000..8bdafe01483--- /dev/null+++ b/ui/litellm-dashboard/src/components/ui_theme_settings.tsx@@ -0,0 +1,207 @@+import React, { useState, useEffect } from "react"+import {+ Card,+ Title,+ Text,+ TextInput,+ Button,+} from "@tremor/react"+import { message } from "antd"+import { useTheme } from "@/contexts/ThemeContext"+import { getProxyBaseUrl } from "@/components/networking"++interface UIThemeSettingsProps {+ userID: string | null;+ userRole: string | null;+ accessToken: string | null;+}++const UIThemeSettings: React.FC<UIThemeSettingsProps> = ({+ userID,+ userRole,+ accessToken,+}) => {+ const { logoUrl, setLogoUrl } = useTheme();+ const [logoUrlInput, setLogoUrlInput] = useState<string>("");+ const [loading, setLoading] = useState(false);++ // Load current settings when component mounts+ useEffect(() => {+ if (accessToken) {+ fetchLogoSettings();+ }+ }, [accessToken]);++ const fetchLogoSettings = async () => {+ try {+ const proxyBaseUrl = getProxyBaseUrl();+ const url = proxyBaseUrl ? `${proxyBaseUrl}/get/ui_theme_settings` : "/get/ui_theme_settings";+ const response = await fetch(url, {+ method: "GET",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });++ if (response.ok) {+ const data = await response.json();+ const logoUrl = data.values?.logo_url || '';+ setLogoUrlInput(logoUrl);+ setLogoUrl(logoUrl || null);+ }+ } catch (error) {+ console.error("Error fetching theme settings:", error);+ }+ };++ const handleSave = async () => {+ setLoading(true);+ try {+ const proxyBaseUrl = getProxyBaseUrl();+ const url = proxyBaseUrl ? `${proxyBaseUrl}/update/ui_theme_settings` : "/update/ui_theme_settings";+ const response = await fetch(url, {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ logo_url: logoUrlInput || null,+ }),+ });++ if (response.ok) {+ message.success("Logo settings updated successfully!");+ setLogoUrl(logoUrlInput || null);+ } else {+ throw new Error("Failed to update settings");+ }+ } catch (error) {+ console.error("Error updating logo settings:", error);+ message.error("Failed to update logo settings");+ } finally {+ setLoading(false);+ }+ };++ const handleReset = async () => {+ setLogoUrlInput("");+ setLogoUrl(null);++ // Save null to backend to clear the logo+ setLoading(true);+ try {+ const proxyBaseUrl = getProxyBaseUrl();+ const url = proxyBaseUrl ? `${proxyBaseUrl}/update/ui_theme_settings` : "/update/ui_theme_settings";+ const response = await fetch(url, {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ logo_url: null,+ }),+ });++ if (response.ok) {+ message.success("Logo reset to default!");+ } else {+ throw new Error("Failed to reset logo");+ }+ } catch (error) {+ console.error("Error resetting logo:", error);+ message.error("Failed to reset logo");+ } finally {+ setLoading(false);+ }+ };++ if (!accessToken) {+ return null;+ }++ return (+ <div className="w-full mx-auto max-w-4xl px-6 py-8">+ <div className="mb-8">+ <Title className="text-2xl font-bold mb-2">Logo Customization</Title>+ <Text className="text-gray-600">+ Customize your LiteLLM admin dashboard with a custom logo.+ </Text>+ </div>++ <Card className="shadow-sm p-6">+ <div className="space-y-6">+ <div>+ <Text className="text-sm font-medium text-gray-700 mb-2 block">+ Custom Logo URL+ </Text>+ <TextInput+ placeholder="https://example.com/logo.png"+ value={logoUrlInput}+ onValueChange={(value) => {+ setLogoUrlInput(value);+ // Update logo in real-time for preview+ setLogoUrl(value || null);+ }}+ className="w-full"+ />+ <Text className="text-xs text-gray-500 mt-1">+ Enter a URL for your custom logo or leave empty to use the default LiteLLM logo+ </Text>+ </div>++ {/* Logo Preview */}+ <div>+ <Text className="text-sm font-medium text-gray-700 mb-2 block">+ Current Logo+ </Text>+ <div className="bg-gray-50 rounded-lg p-6 flex items-center justify-center min-h-[120px]">+ {logoUrlInput ? (+ <img+ src={logoUrlInput}+ alt="Custom logo"+ className="max-w-full max-h-24 object-contain"+ onError={(e) => {+ const target = e.target as HTMLImageElement;+ target.style.display = 'none';+ const fallbackText = document.createElement('div');+ fallbackText.className = 'text-gray-500 text-sm';+ fallbackText.textContent = 'Failed to load image';+ target.parentElement?.appendChild(fallbackText);+ }}+ />+ ) : (+ <Text className="text-gray-500 text-sm">Default LiteLLM logo will be used</Text>+ )}+ </div>+ </div>++ {/* Action Buttons */}+ <div className="flex gap-3 pt-4">+ <Button+ onClick={handleSave}+ loading={loading}+ disabled={loading}+ color="indigo"+ >+ Save Changes+ </Button>+ <Button+ onClick={handleReset}+ loading={loading}+ disabled={loading}+ variant="secondary"+ color="gray"+ >+ Reset to Default+ </Button>+ </div>+ </div>+ </Card>+ </div>+ );+};++export default UIThemeSettings;\ No newline at end of filediff --git a/ui/litellm-dashboard/src/contexts/ThemeContext.tsx b/ui/litellm-dashboard/src/contexts/ThemeContext.tsxnew file mode 100644index 00000000000..619d6a1004a--- /dev/null+++ b/ui/litellm-dashboard/src/contexts/ThemeContext.tsx@@ -0,0 +1,62 @@+import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'+import { getProxyBaseUrl } from '@/components/networking'++interface ThemeContextType {+ logoUrl: string | null;+ setLogoUrl: (url: string | null) => void;+}++const ThemeContext = createContext<ThemeContextType | undefined>(undefined)++export const useTheme = () => {+ const context = useContext(ThemeContext);+ if (!context) {+ throw new Error('useTheme must be used within a ThemeProvider');+ }+ return context;+}++interface ThemeProviderProps {+ children: ReactNode;+ accessToken?: string | null;+}++export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children, accessToken }) => {+ const [logoUrl, setLogoUrl] = useState<string | null>(null);++ // Load logo URL from backend on mount+ useEffect(() => {+ const loadLogoSettings = async () => {+ if (accessToken) {+ try {+ const proxyBaseUrl = getProxyBaseUrl();+ const url = proxyBaseUrl ? `${proxyBaseUrl}/get/ui_theme_settings` : '/get/ui_theme_settings';+ const response = await fetch(url, {+ method: 'GET',+ headers: {+ 'Authorization': `Bearer ${accessToken}`,+ 'Content-Type': 'application/json',+ },+ });++ if (response.ok) {+ const data = await response.json();+ if (data.values?.logo_url) {+ setLogoUrl(data.values.logo_url);+ }+ }+ } catch (error) {+ console.warn('Failed to load logo settings from backend:', error);+ }+ }+ };++ loadLogoSettings();+ }, [accessToken]);++ return (+ <ThemeContext.Provider value={{ logoUrl, setLogoUrl }}>+ {children}+ </ThemeContext.Provider>+ );+};\ No newline at end of file