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
[Proxy + UI] Litellm add reload model api and button (#13464)
Jugal D. Bhatt1270df08a4e0
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 76df4bbd1ee..ef9ef3cb332 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -8858,7 +8858,16 @@ async def config_yaml_endpoint(config_info: ConfigYAML):include_in_schema=False,dependencies=[Depends(user_api_key_auth)],)-async def get_litellm_model_cost_map():+async def get_litellm_model_cost_map(+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ # Check if user is admin+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ raise HTTPException(+ status_code=403,+ detail=f"Access denied. Admin role required. Current role: {user_api_key_dict.user_role}",+ )+try:_model_cost_map = litellm.model_costreturn _model_cost_map@@ -8869,6 +8878,56 @@ async def get_litellm_model_cost_map():)+ "/reload/model_cost_map",+ tags=["model management"],+ dependencies=[Depends(user_api_key_auth)],+ include_in_schema=False,+)+async def reload_model_cost_map(+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ ADMIN ONLY / MASTER KEY Only Endpoint++ Manually reload the model cost map from the remote source.+ This will fetch fresh pricing data from the model_prices_and_context_window.json file.+ """+ # Check if user is admin+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:+ raise HTTPException(+ status_code=403,+ detail=f"Access denied. Admin role required. Current role: {user_api_key_dict.user_role}",+ )++ try:+ from litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map++ # Get the current URL from litellm configuration+ model_cost_map_url = litellm.model_cost_map_url++ # Reload the model cost map+ new_model_cost_map = get_model_cost_map(url=model_cost_map_url)++ # Update the global model_cost variable+ litellm.model_cost = new_model_cost_map++ verbose_proxy_logger.info("Model cost map reloaded successfully")++ return {+ "message": "Model cost map reloaded successfully",+ "status": "success",+ "timestamp": datetime.utcnow().isoformat(),+ "models_count": len(new_model_cost_map) if new_model_cost_map else 0+ }+ except Exception as e:+ verbose_proxy_logger.exception(f"Failed to reload model cost map: {str(e)}")+ raise HTTPException(+ status_code=500,+ detail=f"Failed to reload model cost map: {str(e)}"+ )++@router.get("/", dependencies=[Depends(user_api_key_auth)])async def home(request: Request):return "LiteLLM: RUNNING"diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.pyindex 5ddd59b6167..feb3f154f3a 100644--- a/tests/test_litellm/proxy/test_proxy_server.py+++ b/tests/test_litellm/proxy/test_proxy_server.py@@ -21,6 +21,7 @@ sys.path.insert(import litellmfrom litellm.proxy.proxy_server import app, initialize+from litellm.proxy.auth.user_api_key_auth import user_api_key_authexample_embedding_result = {"object": "list",@@ -1190,3 +1191,166 @@ async def test_chat_completion_result_no_nested_none_values():assert (field not in message), f"Field '{field}' should be excluded when it's None"+++# ============================================================================+# Price Data Reload Tests+# ============================================================================++class TestPriceDataReloadAPI:+ """Test cases for price data reload API endpoints"""++ @pytest.fixture+ def client_with_auth(self):+ """Create a test client with authentication"""+ from litellm.proxy.proxy_server import cleanup_router_config_variables+ from litellm.proxy._types import LitellmUserRoles++ cleanup_router_config_variables()+ filepath = os.path.dirname(os.path.abspath(__file__))+ config_fp = f"{filepath}/test_configs/test_config_no_auth.yaml"+ asyncio.run(initialize(config=config_fp, debug=True))++ # Mock admin user authentication+ mock_auth = MagicMock()+ mock_auth.user_role = LitellmUserRoles.PROXY_ADMIN+ app.dependency_overrides[user_api_key_auth] = lambda: mock_auth++ return TestClient(app)++ def test_reload_model_cost_map_admin_access(self, client_with_auth):+ """Test that admin users can access the reload endpoint"""+ with patch('litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map') as mock_get_map:+ mock_get_map.return_value = {"gpt-3.5-turbo": {"input_cost_per_token": 0.001}}++ response = client_with_auth.post("/reload/model_cost_map")++ assert response.status_code == 200+ data = response.json()+ assert data["status"] == "success"+ assert "message" in data+ assert "timestamp" in data+ assert "models_count" in data++ def test_reload_model_cost_map_non_admin_access(self, client_with_auth):+ """Test that non-admin users cannot access the reload endpoint"""+ # Mock non-admin user+ mock_auth = MagicMock()+ mock_auth.user_role = "user" # Non-admin role+ app.dependency_overrides[user_api_key_auth] = lambda: mock_auth++ response = client_with_auth.post("/reload/model_cost_map")++ assert response.status_code == 403+ data = response.json()+ assert "Access denied" in data["detail"]+ assert "Admin role required" in data["detail"]++ def test_get_model_cost_map_admin_access(self, client_with_auth):+ """Test that admin users can access the get model cost map endpoint"""+ with patch('litellm.model_cost', {"gpt-3.5-turbo": {"input_cost_per_token": 0.001}}):+ response = client_with_auth.get("/get/litellm_model_cost_map")++ assert response.status_code == 200+ data = response.json()+ assert "gpt-3.5-turbo" in data++ def test_get_model_cost_map_non_admin_access(self, client_with_auth):+ """Test that non-admin users cannot access the get model cost map endpoint"""+ # Mock non-admin user+ mock_auth = MagicMock()+ mock_auth.user_role = "user" # Non-admin role+ app.dependency_overrides[user_api_key_auth] = lambda: mock_auth++ response = client_with_auth.get("/get/litellm_model_cost_map")++ assert response.status_code == 403+ data = response.json()+ assert "Access denied" in data["detail"]+ assert "Admin role required" in data["detail"]++ def test_reload_model_cost_map_error_handling(self, client_with_auth):+ """Test error handling in the reload endpoint"""+ with patch('litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map') as mock_get_map:+ mock_get_map.side_effect = Exception("Network error")++ response = client_with_auth.post("/reload/model_cost_map")++ assert response.status_code == 500+ data = response.json()+ assert "Failed to reload model cost map" in data["detail"]+++class TestPriceDataReloadIntegration:+ """Integration tests for the complete price data reload feature"""++ @pytest.fixture+ def client_with_auth(self):+ """Create a test client with authentication"""+ from litellm.proxy.proxy_server import cleanup_router_config_variables+ from litellm.proxy._types import LitellmUserRoles++ cleanup_router_config_variables()+ filepath = os.path.dirname(os.path.abspath(__file__))+ config_fp = f"{filepath}/test_configs/test_config_no_auth.yaml"+ asyncio.run(initialize(config=config_fp, debug=True))++ # Mock admin user authentication+ mock_auth = MagicMock()+ mock_auth.user_role = LitellmUserRoles.PROXY_ADMIN+ app.dependency_overrides[user_api_key_auth] = lambda: mock_auth++ return TestClient(app)++ def test_complete_reload_flow(self, client_with_auth):+ """Test the complete reload flow from API to model cost update"""+ # Mock the model cost map+ mock_cost_map = {+ "gpt-3.5-turbo": {+ "input_cost_per_token": 0.001,+ "output_cost_per_token": 0.002+ },+ "gpt-4": {+ "input_cost_per_token": 0.03,+ "output_cost_per_token": 0.06+ }+ }++ with patch('litellm.litellm_core_utils.get_model_cost_map.get_model_cost_map') as mock_get_map:+ mock_get_map.return_value = mock_cost_map++ # Test reload endpoint+ response = client_with_auth.post("/reload/model_cost_map")+ assert response.status_code == 200++ # Test get endpoint+ response = client_with_auth.get("/get/litellm_model_cost_map")+ assert response.status_code == 200++ def test_config_file_parsing(self):+ """Test parsing of config file with reload settings"""+ config_content = """+general_settings:+ master_key: sk-1234+ model_cost_map_reload_interval: 21600++model_list:+ - model_name: gpt-3.5-turbo+ litellm_params:+ model: gpt-3.5-turbo+ - model_name: gpt-4+ litellm_params:+ model: gpt-4+"""++ # Parse the config+ config = yaml.safe_load(config_content)++ # Verify the reload setting is present+ assert "general_settings" in config+ assert "model_cost_map_reload_interval" in config["general_settings"]+ assert config["general_settings"]["model_cost_map_reload_interval"] == 21600++ # Verify models are present+ assert "model_list" in config+ assert len(config["model_list"]) == 2diff --git a/ui/litellm-dashboard/src/components/model_dashboard.tsx b/ui/litellm-dashboard/src/components/model_dashboard.tsxindex c66ec768449..a4c11560fa7 100644--- a/ui/litellm-dashboard/src/components/model_dashboard.tsx+++ b/ui/litellm-dashboard/src/components/model_dashboard.tsx@@ -71,6 +71,7 @@ import AddModelTab from "./add_model/add_model_tab";import { ModelDataTable } from "./model_dashboard/table";import { columns } from "./model_dashboard/columns";+import PriceDataReload from "./price_data_reload";import HealthCheckComponent from "./model_dashboard/HealthCheckComponent";import PassThroughSettings from "./pass_through_settings";import ModelGroupAliasSettings from "./model_group_alias_settings";@@ -1044,6 +1045,31 @@ const ModelDashboard: React.FC<ModelDashboardProps> = ({<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">+ {/* Price Data Reload Section */}+ <div className="flex justify-between items-center mb-4">+ <div>+ <h2 className="text-lg font-semibold">Model Management</h2>+ <p className="text-sm text-gray-600">+ Manage your models and pricing data+ </p>+ </div>+ {all_admin_roles.includes(userRole) && (+ <PriceDataReload+ accessToken={accessToken}+ onReloadSuccess={() => {+ // Refresh the model map after successful reload+ const fetchModelMap = async () => {+ const data = await modelCostMap(accessToken);+ setModelMap(data);+ };+ fetchModelMap();+ }}+ buttonText="Reload Price Data"+ size="small"+ type="primary"+ />+ )}+ </div>{selectedModelId ? (<ModelInfoViewmodelId={selectedModelId}diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsxindex bdbaebec846..8097f9c4976 100644--- a/ui/litellm-dashboard/src/components/networking.tsx+++ b/ui/litellm-dashboard/src/components/networking.tsx@@ -257,6 +257,27 @@ export const modelCostMap = async (accessToken: string) => {throw error;}};++export const reloadModelCostMap = async (accessToken: string) => {+ try {+ const url = proxyBaseUrl+ ? `${proxyBaseUrl}/reload/model_cost_map`+ : `/reload/model_cost_map`;+ const response = await fetch(url, {+ method: "POST",+ headers: {+ [globalLitellmHeaderName]: `Bearer ${accessToken}`,+ "Content-Type": "application/json",+ },+ });+ const jsonData = await response.json();+ console.log(`Model cost map reload response: ${jsonData}`);+ return jsonData;+ } catch (error) {+ console.error("Failed to reload model cost map:", error);+ throw error;+ }+};export const modelCreateCall = async (accessToken: string,formValues: Modeldiff --git a/ui/litellm-dashboard/src/components/price_data_reload.tsx b/ui/litellm-dashboard/src/components/price_data_reload.tsxnew file mode 100644index 00000000000..e31fa7d37a1--- /dev/null+++ b/ui/litellm-dashboard/src/components/price_data_reload.tsx@@ -0,0 +1,121 @@+import React, { useState } from "react";+import { Button, message, Popconfirm, Tooltip } from "antd";+import { reloadModelCostMap } from "./networking";++interface PriceDataReloadProps {+ accessToken: string;+ onReloadSuccess?: () => void;+ buttonText?: string;+ showIcon?: boolean;+ size?: "small" | "middle" | "large";+ type?: "primary" | "default" | "dashed" | "link" | "text";+ className?: string;+}++const PriceDataReload: React.FC<PriceDataReloadProps> = ({+ accessToken,+ onReloadSuccess,+ buttonText = "Reload Price Data",+ showIcon = true,+ size = "middle",+ type = "primary",+ className = "",+}) => {+ const [isLoading, setIsLoading] = useState(false);++ const handleReload = async () => {+ if (!accessToken) {+ message.error("No access token available");+ return;+ }++ setIsLoading(true);+ try {+ const response = await reloadModelCostMap(accessToken);++ if (response.status === "success") {+ message.success(+ `Price data reloaded successfully! ${response.models_count || 0} models updated.`+ );+ onReloadSuccess?.();+ } else {+ message.error("Failed to reload price data");+ }+ } catch (error) {+ console.error("Error reloading price data:", error);+ message.error("Failed to reload price data. Please try again.");+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <Popconfirm+ title="Reload Price Data"+ description="This will fetch the latest pricing information from the remote source. Continue?"+ onConfirm={handleReload}+ okText="Yes"+ cancelText="No"+ okButtonProps={{+ style: {+ backgroundColor: "#6366f1",+ borderColor: "#6366f1",+ color: "white",+ fontWeight: "500",+ borderRadius: "0.375rem",+ padding: "0.375rem 0.75rem",+ height: "auto",+ fontSize: "0.875rem",+ lineHeight: "1.25rem",+ transition: "all 0.2s ease-in-out",+ },+ onMouseEnter: (e) => {+ e.currentTarget.style.backgroundColor = "#4f46e5";+ e.currentTarget.style.borderColor = "#4f46e5";+ },+ onMouseLeave: (e) => {+ e.currentTarget.style.backgroundColor = "#6366f1";+ e.currentTarget.style.borderColor = "#6366f1";+ },+ }}+ >+ <Tooltip title="Reload latest pricing data from remote source">+ <Button+ type={type}+ size={size}+ loading={isLoading}+ className={className}+ style={{+ backgroundColor: "#6366f1", // Tremor primary color+ borderColor: "#6366f1",+ color: "white",+ fontWeight: "500",+ borderRadius: "0.5rem",+ padding: "0.5rem 1rem",+ height: "auto",+ display: "inline-flex",+ alignItems: "center",+ justifyContent: "center",+ gap: "0.5rem",+ fontSize: "0.875rem",+ lineHeight: "1.25rem",+ transition: "all 0.2s ease-in-out",+ boxShadow: "0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = "#4f46e5";+ e.currentTarget.style.borderColor = "#4f46e5";+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = "#6366f1";+ e.currentTarget.style.borderColor = "#6366f1";+ }}+ >+ {showIcon ? "↻ " : ""}{buttonText}+ </Button>+ </Tooltip>+ </Popconfirm>+ );+};++export default PriceDataReload;\ No newline at end of file