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(proxy): add custom favicon support\n\nAdd ability to configure a custom favicon for the litellm proxy UI.\n\n- Add favicon_url field to UIThemeConfig model\n- Add LITELLM_FAVICON_URL env var support\n- Add /get_favicon endpoint to serve custom favicons\n- Update ThemeContext to dynamically set favicon\n- Add favicon URL input to UI theme settings page\n- Add comprehensive tests\n\nCloses #8323 (#21653)
Zhenting Huang647ea3bfcbea
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 1fa0107469b..1a09ed2e0a6 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -10742,6 +10742,81 @@ async def get_image():return FileResponse(logo_path, media_type="image/jpeg")[email protected]("/get_favicon", include_in_schema=False)+async def get_favicon():+ """Get custom favicon for the admin UI."""+ from fastapi.responses import Response++ current_dir = os.path.dirname(os.path.abspath(__file__))+ default_favicon = os.path.join(+ current_dir, "_experimental", "out", "favicon.ico"+ )++ favicon_url = os.getenv("LITELLM_FAVICON_URL", "")++ if not favicon_url:+ if os.path.exists(default_favicon):+ return FileResponse(default_favicon, media_type="image/x-icon")+ raise HTTPException(+ status_code=404, detail="Default favicon not found"+ )++ if favicon_url.startswith(("http://", "https://")):+ try:+ from litellm.llms.custom_httpx.http_handler import (+ get_async_httpx_client,+ )+ from litellm.types.llms.custom_http import httpxSpecialProvider++ async_client = get_async_httpx_client(+ llm_provider=httpxSpecialProvider.UI,+ params={"timeout": 5.0},+ )+ response = await async_client.get(favicon_url)+ if response.status_code == 200:+ content_type = response.headers.get(+ "content-type", "image/x-icon"+ )+ return Response(+ content=response.content,+ media_type=content_type,+ )+ else:+ verbose_proxy_logger.warning(+ "Failed to fetch favicon from %s: status %s",+ favicon_url,+ response.status_code,+ )+ if os.path.exists(default_favicon):+ return FileResponse(+ default_favicon, media_type="image/x-icon"+ )+ raise HTTPException(+ status_code=404, detail="Favicon not found"+ )+ except HTTPException:+ raise+ except Exception as e:+ verbose_proxy_logger.debug(+ "Error downloading favicon from %s: %s", favicon_url, e+ )+ if os.path.exists(default_favicon):+ return FileResponse(+ default_favicon, media_type="image/x-icon"+ )+ raise HTTPException(+ status_code=404, detail="Favicon not found"+ )+ else:+ if os.path.exists(favicon_url):+ return FileResponse(favicon_url, media_type="image/x-icon")+ if os.path.exists(default_favicon):+ return FileResponse(default_favicon, media_type="image/x-icon")+ raise HTTPException(+ status_code=404, detail="Favicon not found"+ )++#### INVITATION MANAGEMENT ####diff --git a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.pyindex 6d32310940b..9c85f4f148b 100644--- a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py+++ b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py@@ -30,6 +30,12 @@ class UIThemeConfig(BaseModel):description="URL or path to custom logo image. Can be a local file path or HTTP/HTTPS URL",)+ # Favicon configuration+ favicon_url: Optional[str] = Field(+ default=None,+ description="URL to custom favicon image. Must be an HTTP/HTTPS URL to a .ico, .png, or .svg file",+ )+class SettingsResponse(BaseModel):"""Base response model for settings with values and schema information"""@@ -788,6 +794,27 @@ async def update_ui_theme_settings(theme_config: UIThemeConfig):del os.environ["UI_LOGO_PATH"]verbose_proxy_logger.debug("Removed UI_LOGO_PATH from environment")+ # Update LITELLM_FAVICON_URL environment variable if favicon_url is provided+ favicon_url = theme_data.get("favicon_url")+ verbose_proxy_logger.debug(f"Updating favicon_url: {favicon_url}")++ if (+ favicon_url and isinstance(favicon_url, str) and favicon_url.strip()+ ): # Check if favicon_url exists and is not empty/whitespace+ config["environment_variables"]["LITELLM_FAVICON_URL"] = favicon_url+ os.environ["LITELLM_FAVICON_URL"] = favicon_url+ verbose_proxy_logger.debug(f"Set LITELLM_FAVICON_URL to: {favicon_url}")+ else:+ # Remove the environment variable to restore default favicon+ if "LITELLM_FAVICON_URL" in config.get("environment_variables", {}):+ del config["environment_variables"]["LITELLM_FAVICON_URL"]+ verbose_proxy_logger.debug("Removed LITELLM_FAVICON_URL from config")+ if "LITELLM_FAVICON_URL" in os.environ:+ del os.environ["LITELLM_FAVICON_URL"]+ verbose_proxy_logger.debug(+ "Removed LITELLM_FAVICON_URL from environment"+ )+# Handle environment variable encryption if neededstored_config = config.copy()if (@@ -803,7 +830,7 @@ async def update_ui_theme_settings(theme_config: UIThemeConfig):await proxy_config.save_config(new_config=stored_config)return {- "message": "Logo settings updated successfully.",+ "message": "UI theme settings updated successfully.","status": "success","theme_config": theme_data,}diff --git a/tests/proxy_unit_tests/test_get_favicon.py b/tests/proxy_unit_tests/test_get_favicon.pynew file mode 100644index 00000000000..f17787e740d--- /dev/null+++ b/tests/proxy_unit_tests/test_get_favicon.py@@ -0,0 +1,75 @@+import os+import sys+from unittest import mock++sys.path.insert(0, os.path.abspath("../.."))++import httpx+import pytest++from litellm.proxy.proxy_server import app+++async def test_get_favicon_default():+ """Test that get_favicon returns the default favicon when no URL set."""+ os.environ.pop("LITELLM_FAVICON_URL", None)++ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://testserver"+ ) as ac:+ response = await ac.get("/get_favicon")++ assert response.status_code in [200, 404]+ if response.status_code == 200:+ assert response.headers["content-type"] == "image/x-icon"+++async def test_get_favicon_with_custom_url():+ """Test that get_favicon fetches from a custom URL."""+ os.environ["LITELLM_FAVICON_URL"] = "https://example.com/favicon.ico"++ mock_response = mock.Mock()+ mock_response.status_code = 200+ mock_response.content = b"\x00\x00\x01\x00"+ mock_response.headers = {"content-type": "image/x-icon"}++ try:+ with mock.patch(+ "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get"+ ) as mock_get:+ mock_get.return_value = mock_response++ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://testserver",+ ) as ac:+ response = await ac.get("/get_favicon")++ assert response.status_code == 200+ assert response.headers["content-type"] == "image/x-icon"+ finally:+ os.environ.pop("LITELLM_FAVICON_URL", None)+++async def test_get_favicon_url_error_fallback():+ """Test that get_favicon falls back to default on error."""+ os.environ["LITELLM_FAVICON_URL"] = "https://invalid.com/favicon.ico"++ try:+ with mock.patch(+ "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get"+ ) as mock_get:+ mock_get.side_effect = httpx.ConnectError("unreachable")++ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://testserver",+ ) as ac:+ response = await ac.get("/get_favicon")++ assert response.status_code in [200, 404]+ finally:+ os.environ.pop("LITELLM_FAVICON_URL", None)diff --git a/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py b/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.pyindex 60bdb7d12cb..c36270751d8 100644--- a/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py+++ b/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py@@ -666,6 +666,119 @@ class TestProxySettingEndpoints:assert "UI_LOGO_PATH" in updated_config["environment_variables"]assert mock_proxy_config["save_call_count"]() == 1+ def test_update_ui_theme_settings_with_favicon(+ self, mock_proxy_config, mock_auth, monkeypatch+ ):+ """Test updating UI theme settings with favicon_url"""+ monkeypatch.setenv("LITELLM_SALT_KEY", "test_salt_key")+ monkeypatch.setattr(+ "litellm.proxy.proxy_server.store_model_in_db", True+ )++ new_theme = {+ "logo_url": "https://example.com/new-logo.png",+ "favicon_url": "https://example.com/custom-favicon.ico",+ }++ response = client.patch(+ "/update/ui_theme_settings", json=new_theme+ )++ assert response.status_code == 200+ data = response.json()++ assert data["status"] == "success"+ assert (+ data["theme_config"]["logo_url"]+ == "https://example.com/new-logo.png"+ )+ assert (+ data["theme_config"]["favicon_url"]+ == "https://example.com/custom-favicon.ico"+ )++ updated_config = mock_proxy_config["config"]+ assert "UI_LOGO_PATH" in updated_config["environment_variables"]+ assert (+ "LITELLM_FAVICON_URL"+ in updated_config["environment_variables"]+ )+ assert (+ updated_config["environment_variables"][+ "LITELLM_FAVICON_URL"+ ]+ == "https://example.com/custom-favicon.ico"+ )++ def test_update_ui_theme_settings_clear_favicon(+ self, mock_proxy_config, mock_auth, monkeypatch+ ):+ """Test clearing favicon_url from UI theme settings"""+ monkeypatch.setenv("LITELLM_SALT_KEY", "test_salt_key")+ monkeypatch.setattr(+ "litellm.proxy.proxy_server.store_model_in_db", True+ )++ new_theme = {+ "favicon_url": "https://example.com/custom-favicon.ico",+ }+ response = client.patch(+ "/update/ui_theme_settings", json=new_theme+ )+ assert response.status_code == 200++ clear_theme = {"favicon_url": None}+ response = client.patch(+ "/update/ui_theme_settings", json=clear_theme+ )+ assert response.status_code == 200+ data = response.json()+ assert data["status"] == "success"+ assert "LITELLM_FAVICON_URL" not in os.environ++ def test_get_ui_theme_settings_includes_favicon_schema(+ self, mock_proxy_config+ ):+ """Test UI theme settings includes favicon_url in schema"""+ response = client.get("/get/ui_theme_settings")++ assert response.status_code == 200+ data = response.json()++ assert "values" in data+ assert "field_schema" in data+ assert "properties" in data["field_schema"]+ assert "favicon_url" in data["field_schema"]["properties"]+ assert (+ "description"+ in data["field_schema"]["properties"]["favicon_url"]+ )++ def test_get_ui_theme_settings_with_favicon_configured(+ self, mock_proxy_config+ ):+ """Test getting UI theme settings when favicon is configured"""+ mock_proxy_config["config"]["litellm_settings"][+ "ui_theme_config"+ ] = {+ "logo_url": "https://example.com/logo.png",+ "favicon_url": "https://example.com/favicon.ico",+ }++ response = client.get("/get/ui_theme_settings")++ assert response.status_code == 200+ data = response.json()++ assert (+ data["values"]["logo_url"]+ == "https://example.com/logo.png"+ )+ assert (+ data["values"]["favicon_url"]+ == "https://example.com/favicon.ico"+ )+def test_get_ui_settings(self, mock_auth, monkeypatch):"""Test retrieving UI settings with allowlist sanitization"""from unittest.mock import AsyncMock, MagicMockdiff --git a/ui/litellm-dashboard/src/components/ui_theme_settings.tsx b/ui/litellm-dashboard/src/components/ui_theme_settings.tsxindex 636163d1d70..94bc0c9ebe6 100644--- a/ui/litellm-dashboard/src/components/ui_theme_settings.tsx+++ b/ui/litellm-dashboard/src/components/ui_theme_settings.tsx@@ -11,18 +11,16 @@ interface UIThemeSettingsProps {}const UIThemeSettings: React.FC<UIThemeSettingsProps> = ({ userID, userRole, accessToken }) => {- const { logoUrl, setLogoUrl } = useTheme();+ const { logoUrl, setLogoUrl, faviconUrl, setFaviconUrl } = useTheme();const [logoUrlInput, setLogoUrlInput] = useState<string>("");+ const [faviconUrlInput, setFaviconUrlInput] = useState<string>("");const [loading, setLoading] = useState(false);- // Load current settings when component mountsuseEffect(() => {- if (accessToken) {- fetchLogoSettings();- }+ if (accessToken) { fetchThemeSettings(); }}, [accessToken]);- const fetchLogoSettings = async () => {+ const fetchThemeSettings = async () => {try {const proxyBaseUrl = getProxyBaseUrl();const url = proxyBaseUrl ? `${proxyBaseUrl}/get/ui_theme_settings` : "/get/ui_theme_settings";@@ -33,12 +31,12 @@ const UIThemeSettings: React.FC<UIThemeSettingsProps> = ({ userID, userRole, acc"Content-Type": "application/json",},});-if (response.ok) {const data = await response.json();- const logoUrl = data.values?.logo_url || "";- setLogoUrlInput(logoUrl);- setLogoUrl(logoUrl || null);+ setLogoUrlInput(data.values?.logo_url || "");+ setFaviconUrlInput(data.values?.favicon_url || "");+ setLogoUrl(data.values?.logo_url || null);+ setFaviconUrl(data.values?.favicon_url || null);}} catch (error) {console.error("Error fetching theme settings:", error);@@ -58,28 +56,23 @@ const UIThemeSettings: React.FC<UIThemeSettingsProps> = ({ userID, userRole, acc},body: JSON.stringify({logo_url: logoUrlInput || null,+ favicon_url: faviconUrlInput || null,}),});-if (response.ok) {- NotificationsManager.success("Logo settings updated successfully!");+ NotificationsManager.success("Theme settings updated successfully!");setLogoUrl(logoUrlInput || null);- } else {- throw new Error("Failed to update settings");- }+ setFaviconUrl(faviconUrlInput || null);+ } else { throw new Error("Failed to update settings"); }} catch (error) {- console.error("Error updating logo settings:", error);- NotificationsManager.fromBackend("Failed to update logo settings");- } finally {- setLoading(false);- }+ console.error("Error updating theme settings:", error);+ NotificationsManager.fromBackend("Failed to update theme settings");+ } finally { setLoading(false); }};const handleReset = async () => {- setLogoUrlInput("");- setLogoUrl(null);-- // Save null to backend to clear the logo+ setLogoUrlInput(""); setFaviconUrlInput("");+ setLogoUrl(null); setFaviconUrl(null);setLoading(true);try {const proxyBaseUrl = getProxyBaseUrl();@@ -90,86 +83,41 @@ const UIThemeSettings: React.FC<UIThemeSettingsProps> = ({ userID, userRole, acc[getGlobalLitellmHeaderName()]: `Bearer ${accessToken}`,"Content-Type": "application/json",},- body: JSON.stringify({- logo_url: null,- }),+ body: JSON.stringify({ logo_url: null, favicon_url: null }),});-- if (response.ok) {- NotificationsManager.success("Logo reset to default!");- } else {- throw new Error("Failed to reset logo");- }+ if (response.ok) { NotificationsManager.success("Theme settings reset to default!"); }+ else { throw new Error("Failed to reset"); }} catch (error) {- console.error("Error resetting logo:", error);- NotificationsManager.fromBackend("Failed to reset logo");- } finally {- setLoading(false);- }+ console.error("Error resetting theme settings:", error);+ NotificationsManager.fromBackend("Failed to reset theme settings");+ } finally { setLoading(false); }};- if (!accessToken) {- return null;- }+ 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>+ <Title className="text-2xl font-bold mb-2">UI Theme Customization</Title>+ <Text className="text-gray-600">Customize your LiteLLM admin dashboard with a custom logo and favicon.</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>+ <TextInput placeholder="https://example.com/logo.png" value={logoUrlInput}+ onValueChange={(v) => { setLogoUrlInput(v); setLogoUrl(v || null); }} className="w-full" />+ <Text className="text-xs text-gray-500 mt-1">Enter a URL for your custom logo or leave empty for default</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>+ <Text className="text-sm font-medium text-gray-700 mb-2 block">Custom Favicon URL</Text>+ <TextInput placeholder="https://example.com/favicon.ico" value={faviconUrlInput}+ onValueChange={(v) => { setFaviconUrlInput(v); setFaviconUrl(v || null); }} className="w-full" />+ <Text className="text-xs text-gray-500 mt-1">Enter a URL for your custom favicon (.ico, .png, or .svg) or leave empty for default</Text></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>+ <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>diff --git a/ui/litellm-dashboard/src/contexts/ThemeContext.tsx b/ui/litellm-dashboard/src/contexts/ThemeContext.tsxindex 1204b7b0deb..8f34269ad4d 100644--- a/ui/litellm-dashboard/src/contexts/ThemeContext.tsx+++ b/ui/litellm-dashboard/src/contexts/ThemeContext.tsx@@ -4,6 +4,8 @@ import { getProxyBaseUrl } from "@/components/networking";interface ThemeContextType {logoUrl: string | null;setLogoUrl: (url: string | null) => void;+ faviconUrl: string | null;+ setFaviconUrl: (url: string | null) => void;}const ThemeContext = createContext<ThemeContextType | undefined>(undefined);@@ -23,20 +25,16 @@ interface ThemeProviderProps {export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children, accessToken }) => {const [logoUrl, setLogoUrl] = useState<string | null>(null);+ const [faviconUrl, setFaviconUrl] = useState<string | null>(null);- // Load logo URL from backend on mount- // Note: /get/ui_theme_settings is now a public endpoint (no auth required)- // so all users can see custom branding set by adminsuseEffect(() => {- const loadLogoSettings = async () => {+ const loadThemeSettings = 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: {- "Content-Type": "application/json",- },+ headers: { "Content-Type": "application/json" },});if (response.ok) {@@ -44,14 +42,37 @@ export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children, accessToif (data.values?.logo_url) {setLogoUrl(data.values.logo_url);}+ if (data.values?.favicon_url) {+ setFaviconUrl(data.values.favicon_url);+ }}} catch (error) {- console.warn("Failed to load logo settings from backend:", error);+ console.warn("Failed to load theme settings from backend:", error);}};- loadLogoSettings();+ loadThemeSettings();}, []);- return <ThemeContext.Provider value={{ logoUrl, setLogoUrl }}>{children}</ThemeContext.Provider>;+ useEffect(() => {+ if (faviconUrl) {+ const existingLinks = document.querySelectorAll("link[rel*='icon']");+ if (existingLinks.length > 0) {+ existingLinks.forEach((link) => {+ (link as HTMLLinkElement).href = faviconUrl;+ });+ } else {+ const link = document.createElement("link");+ link.rel = "icon";+ link.href = faviconUrl;+ document.head.appendChild(link);+ }+ }+ }, [faviconUrl]);++ return (+ <ThemeContext.Provider value={{ logoUrl, setLogoUrl, faviconUrl, setFaviconUrl }}>+ {children}+ </ThemeContext.Provider>+ );};