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
[Fix] Management Endpoints - Fixes inconsistent error responses in customer management endpoints. Non-existent user errors now return proper 404 status codes with consistent error schema format across all endpoints. (#16450)
Ishaan Jaffdc76b6c76e8f
diff --git a/litellm/proxy/management_endpoints/customer_endpoints.py b/litellm/proxy/management_endpoints/customer_endpoints.pyindex c653b3baf88..4b6ceefb751 100644--- a/litellm/proxy/management_endpoints/customer_endpoints.py+++ b/litellm/proxy/management_endpoints/customer_endpoints.py@@ -20,6 +20,7 @@ import litellmfrom litellm._logging import verbose_proxy_loggerfrom litellm.proxy._types import *from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.utils import handle_exception_on_proxyrouter = APIRouter()@@ -305,22 +306,7 @@ async def new_end_user(code=400,param="user_id",)-- if isinstance(e, HTTPException):- raise ProxyException(- message=getattr(e, "detail", f"Internal Server Error({str(e)})"),- type="internal_error",- param=getattr(e, "param", "None"),- code=getattr(e, "status_code", status.HTTP_500_INTERNAL_SERVER_ERROR),- )- elif isinstance(e, ProxyException):- raise e- raise ProxyException(- message="Internal Server Error, " + str(e),- type="internal_error",- param=getattr(e, "param", "None"),- code=status.HTTP_500_INTERNAL_SERVER_ERROR,- )+ raise handle_exception_on_proxy(e)@router.get(@@ -352,25 +338,35 @@ async def end_user_info(-H 'Authorization: Bearer sk-1234'```"""- from litellm.proxy.proxy_server import prisma_client-- if prisma_client is None:- raise HTTPException(- status_code=500,- detail={"error": CommonProxyErrors.db_not_connected_error.value},- )+ try:+ from litellm.proxy.proxy_server import prisma_client- user_info = await prisma_client.db.litellm_endusertable.find_first(- where={"user_id": end_user_id}, include={"litellm_budget_table": True}- )+ if prisma_client is None:+ raise HTTPException(+ status_code=500,+ detail={"error": CommonProxyErrors.db_not_connected_error.value},+ )- if user_info is None:- raise HTTPException(- status_code=400,- detail={"error": "End User Id={} does not exist in db".format(end_user_id)},+ user_info = await prisma_client.db.litellm_endusertable.find_first(+ where={"user_id": end_user_id}, include={"litellm_budget_table": True})- return user_info.model_dump(exclude_none=True)+ if user_info is None:+ raise ProxyException(+ message="End User Id={} does not exist in db".format(end_user_id),+ type="not_found",+ code=404,+ param="end_user_id",+ )+ return user_info.model_dump(exclude_none=True)++ except Exception as e:+ verbose_proxy_logger.exception(+ "litellm.proxy.management_endpoints.customer_endpoints.end_user_info(): Exception occured - {}".format(+ str(e)+ )+ )+ raise handle_exception_on_proxy(e)@router.post("/customer/update",@@ -441,11 +437,11 @@ async def update_end_user()if end_user_table_data is None:- raise HTTPException(- status_code=400,- detail={- "error": "End User Id={} does not exist in db".format(data.user_id)- },+ raise ProxyException(+ message="End User Id={} does not exist in db".format(data.user_id),+ type="not_found",+ code=404,+ param="user_id",)end_user_table_data_typed = LiteLLM_EndUserTable(@@ -524,22 +520,7 @@ async def update_end_user(str(e)))- if isinstance(e, HTTPException):- raise ProxyException(- message=getattr(e, "detail", f"Internal Server Error({str(e)})"),- type="internal_error",- param=getattr(e, "param", "None"),- code=getattr(e, "status_code", status.HTTP_500_INTERNAL_SERVER_ERROR),- )- elif isinstance(e, ProxyException):- raise e- raise ProxyException(- message="Internal Server Error, " + str(e),- type="internal_error",- param=getattr(e, "param", "None"),- code=status.HTTP_500_INTERNAL_SERVER_ERROR,- )- pass+ raise handle_exception_on_proxy(e)@router.post(@@ -587,17 +568,29 @@ async def delete_end_user(and isinstance(data.user_ids, list)and len(data.user_ids) > 0):- response = await prisma_client.db.litellm_endusertable.delete_many(+ # First check if all users exist+ existing_users = await prisma_client.db.litellm_endusertable.find_many(where={"user_id": {"in": data.user_ids}})- if response is None:- raise ValueError(- f"Failed deleting customer data. User ID does not exist passed user_id={data.user_ids}"- )- if response != len(data.user_ids):- raise ValueError(- f"Failed deleting all customer data. User ID does not exist passed user_id={data.user_ids}. Deleted {response} customers, passed {len(data.user_ids)} customers"+ existing_user_ids = {user.user_id for user in existing_users}+ missing_user_ids = [+ user_id for user_id in data.user_ids if user_id not in existing_user_ids+ ]++ if missing_user_ids:+ raise ProxyException(+ message="End User Id(s)={} do not exist in db".format(+ ", ".join(missing_user_ids)+ ),+ type="not_found",+ code=404,+ param="user_ids",)++ # All users exist, proceed with deletion+ response = await prisma_client.db.litellm_endusertable.delete_many(+ where={"user_id": {"in": data.user_ids}}+ )verbose_proxy_logger.debug(f"received response from updating prisma client. response={response}")@@ -616,24 +609,7 @@ async def delete_end_user(str(e)))- verbose_proxy_logger.debug(traceback.format_exc())- if isinstance(e, HTTPException):- raise ProxyException(- message=getattr(e, "detail", f"Internal Server Error({str(e)})"),- type="internal_error",- param=getattr(e, "param", "None"),- code=getattr(e, "status_code", status.HTTP_500_INTERNAL_SERVER_ERROR),- )- elif isinstance(e, ProxyException):- raise e- raise ProxyException(- message="Internal Server Error, " + str(e),- type="internal_error",- param=getattr(e, "param", "None"),- code=status.HTTP_500_INTERNAL_SERVER_ERROR,- )- pass-+ raise handle_exception_on_proxy(e)@router.get("/customer/list",@@ -661,32 +637,41 @@ async def list_end_user(```"""- from litellm.proxy.proxy_server import prisma_client+ try:+ from litellm.proxy.proxy_server import prisma_client- if (- user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN- and user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY- ):- raise HTTPException(- status_code=401,- detail={- "error": "Admin-only endpoint. Your user role={}".format(- user_api_key_dict.user_role- )- },- )+ if (+ user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN+ and user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY+ ):+ raise HTTPException(+ status_code=401,+ detail={+ "error": "Admin-only endpoint. Your user role={}".format(+ user_api_key_dict.user_role+ )+ },+ )- if prisma_client is None:- raise HTTPException(- status_code=400,- detail={"error": CommonProxyErrors.db_not_connected_error.value},- )+ if prisma_client is None:+ raise HTTPException(+ status_code=400,+ detail={"error": CommonProxyErrors.db_not_connected_error.value},+ )- response = await prisma_client.db.litellm_endusertable.find_many(- include={"litellm_budget_table": True}- )+ response = await prisma_client.db.litellm_endusertable.find_many(+ include={"litellm_budget_table": True}+ )- returned_response: List[LiteLLM_EndUserTable] = []- for item in response:- returned_response.append(LiteLLM_EndUserTable(**item.model_dump()))- return returned_response+ returned_response: List[LiteLLM_EndUserTable] = []+ for item in response:+ returned_response.append(LiteLLM_EndUserTable(**item.model_dump()))+ return returned_response++ except Exception as e:+ verbose_proxy_logger.exception(+ "litellm.proxy.management_endpoints.customer_endpoints.list_end_user(): Exception occured - {}".format(+ str(e)+ )+ )+ raise handle_exception_on_proxy(e)\ No newline at end of filediff --git a/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.pyindex 6382976c361..86a6ceec25e 100644--- a/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.py@@ -1,19 +1,35 @@from unittest.mock import AsyncMock, patchimport pytest-from fastapi import FastAPI, HTTPException+from fastapi import FastAPI, HTTPException, Request, status+from fastapi.responses import JSONResponsefrom fastapi.testclient import TestClientfrom litellm.proxy._types import (LiteLLM_BudgetTable,LiteLLM_EndUserTable,LitellmUserRoles,+ ProxyException,)from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuthfrom litellm.proxy.management_endpoints.customer_endpoints import router-from litellm.proxy.proxy_server import ProxyExceptionapp = FastAPI()++[email protected]_handler(ProxyException)+async def openai_exception_handler(request: Request, exc: ProxyException):+ headers = exc.headers+ error_dict = exc.to_dict()+ return JSONResponse(+ status_code=(+ int(exc.code) if exc.code else status.HTTP_500_INTERNAL_SERVER_ERROR+ ),+ content={"error": error_dict},+ headers=headers,+ )++app.include_router(router)client = TestClient(app)@@ -67,6 +83,9 @@ def test_update_customer_success(mock_prisma_client, mock_user_api_key_auth):def test_update_customer_not_found(mock_prisma_client, mock_user_api_key_auth):+ """+ Test that update_end_user raises a 404 ProxyException when user_id does not exist.+ """# Mock the database response to return None (user not found)mock_prisma_client.db.litellm_endusertable.find_first = AsyncMock(return_value=None)@@ -74,14 +93,211 @@ def test_update_customer_not_found(mock_prisma_client, mock_user_api_key_auth):test_data = {"user_id": "non-existent-user", "alias": "Test User"}# Make the request- try:- response = client.post(- "/customer/update",- json=test_data,- headers={"Authorization": "Bearer test-key"},- )- except Exception as e:- print(e, type(e))- assert isinstance(e, ProxyException)- assert int(e.code) == 400- assert "End User Id=non-existent-user does not exist in db" in e.message+ response = client.post(+ "/customer/update",+ json=test_data,+ headers={"Authorization": "Bearer test-key"},+ )++ # Assert response+ assert response.status_code == 404+ response_json = response.json()+ assert "error" in response_json+ assert response_json["error"]["message"] == "End User Id=non-existent-user does not exist in db"+ assert response_json["error"]["type"] == "not_found"+ assert response_json["error"]["param"] == "user_id"+ assert response_json["error"]["code"] == "404"+++def test_info_customer_not_found(mock_prisma_client, mock_user_api_key_auth):+ """+ Test that end_user_info raises a 404 ProxyException when end_user_id does not exist.+ """+ # Mock the database response to return None (user not found)+ mock_prisma_client.db.litellm_endusertable.find_first = AsyncMock(return_value=None)++ # Make the request+ response = client.get(+ "/customer/info?end_user_id=non-existent-user",+ headers={"Authorization": "Bearer test-key"},+ )++ # Assert response+ assert response.status_code == 404+ response_json = response.json()+ assert "error" in response_json+ assert response_json["error"]["message"] == "End User Id=non-existent-user does not exist in db"+ assert response_json["error"]["type"] == "not_found"+ assert response_json["error"]["param"] == "end_user_id"+ assert response_json["error"]["code"] == "404"+++def test_delete_customer_not_found(mock_prisma_client, mock_user_api_key_auth):+ """+ Test that delete_end_user raises a 404 ProxyException when user_ids do not exist.+ """+ # Mock the database response to return empty list (no users found)+ mock_prisma_client.db.litellm_endusertable.find_many = AsyncMock(return_value=[])++ # Test data+ test_data = {"user_ids": ["non-existent-user-1", "non-existent-user-2"]}++ # Make the request+ response = client.post(+ "/customer/delete",+ json=test_data,+ headers={"Authorization": "Bearer test-key"},+ )++ # Assert response+ assert response.status_code == 404+ response_json = response.json()+ assert "error" in response_json+ assert "do not exist in db" in response_json["error"]["message"]+ assert "non-existent-user-1" in response_json["error"]["message"]+ assert response_json["error"]["type"] == "not_found"+ assert response_json["error"]["param"] == "user_ids"+ assert response_json["error"]["code"] == "404"+++def test_error_schema_consistency(mock_prisma_client, mock_user_api_key_auth):+ """+ Test that all customer endpoints return the same error schema format.+ All ProxyException errors should have: message, type, param, and code fields.+ """++ def validate_error_schema(response_json):+ assert "error" in response_json, "Response should have 'error' key"+ error = response_json["error"]+ assert "message" in error, "Error should have 'message' field"+ assert "type" in error, "Error should have 'type' field"+ assert "param" in error, "Error should have 'param' field"+ assert "code" in error, "Error should have 'code' field"+ assert isinstance(error["message"], str), "message should be a string"+ assert isinstance(error["type"], str), "type should be a string"+ assert isinstance(error["code"], str), "code should be a string"+ return error++ # Test /customer/info - not found error+ mock_prisma_client.db.litellm_endusertable.find_first = AsyncMock(return_value=None)+ response = client.get(+ "/customer/info?end_user_id=non-existent",+ headers={"Authorization": "Bearer test-key"},+ )+ error = validate_error_schema(response.json())+ assert error["type"] == "not_found"+ assert error["code"] == "404"++ # Test /customer/update - not found error+ mock_prisma_client.db.litellm_endusertable.find_first = AsyncMock(return_value=None)+ response = client.post(+ "/customer/update",+ json={"user_id": "non-existent", "alias": "Test"},+ headers={"Authorization": "Bearer test-key"},+ )+ error = validate_error_schema(response.json())+ assert error["type"] == "not_found"+ assert error["code"] == "404"++ # Test /customer/delete - not found error+ mock_prisma_client.db.litellm_endusertable.find_many = AsyncMock(return_value=[])+ response = client.post(+ "/customer/delete",+ json={"user_ids": ["non-existent"]},+ headers={"Authorization": "Bearer test-key"},+ )+ error = validate_error_schema(response.json())+ assert error["type"] == "not_found"+ assert error["code"] == "404"++ # Test /customer/new - duplicate user error+ from unittest.mock import MagicMock++ mock_end_user = LiteLLM_EndUserTable(+ user_id="existing-user", alias="Existing User", blocked=False+ )+ mock_prisma_client.db.litellm_endusertable.create = AsyncMock(+ side_effect=Exception("Unique constraint failed on the fields: (`user_id`)")+ )+ response = client.post(+ "/customer/new",+ json={"user_id": "existing-user"},+ headers={"Authorization": "Bearer test-key"},+ )+ error = validate_error_schema(response.json())+ assert error["type"] == "bad_request"+ assert error["code"] == "400"+++def test_customer_endpoints_error_schema_consistency(mock_prisma_client, mock_user_api_key_auth):+ """+ Test the exact scenarios from the curl examples provided.++ Scenario 1: GET /end_user/info with non-existent user+ OLD (incorrect): {"detail":{"error":"End User Id=... does not exist in db"}}+ NEW (correct): {"error":{"message":"...","type":"not_found","param":"end_user_id","code":"404"}}++ Scenario 2: POST /end_user/new with existing user+ Expected: {"error":{"message":"...","type":"bad_request","param":"user_id","code":"400"}}++ Both should use the same error format structure.+ """++ # Scenario 1: GET /end_user/info with non-existent user+ # Should return 404 with proper error schema+ mock_prisma_client.db.litellm_endusertable.find_first = AsyncMock(return_value=None)++ response1 = client.get(+ "/end_user/info?end_user_id=fake-test-end-user-michaels-local-testng",+ headers={"Authorization": "Bearer test-key"},+ )++ assert response1.status_code == 404, "Should return 404 for non-existent user"+ response1_json = response1.json()+++ # Should have the correct format with {"error": {...}}+ assert "error" in response1_json, "Should have top-level 'error' key"+ error1 = response1_json["error"]+ assert "message" in error1, "Error should have 'message' field"+ assert "type" in error1, "Error should have 'type' field"+ assert "param" in error1, "Error should have 'param' field"+ assert "code" in error1, "Error should have 'code' field"+ assert error1["type"] == "not_found"+ assert error1["code"] == "404"+ assert "does not exist in db" in error1["message"]++ # Scenario 2: POST /end_user/new with existing user+ # Should return 400 with proper error schema+ mock_prisma_client.db.litellm_endusertable.create = AsyncMock(+ side_effect=Exception("Unique constraint failed on the fields: (`user_id`)")+ )++ response2 = client.post(+ "/end_user/new",+ json={"user_id": "fake-test-end-user-michaels-local-testing", "budget_id": "Tier0"},+ headers={"Authorization": "Bearer test-key"},+ )++ assert response2.status_code == 400, "Should return 400 for duplicate user"+ response2_json = response2.json()++ # Should have the same error structure as Scenario 1+ assert "error" in response2_json, "Should have top-level 'error' key"+ error2 = response2_json["error"]+ assert "message" in error2, "Error should have 'message' field"+ assert "type" in error2, "Error should have 'type' field"+ assert "param" in error2, "Error should have 'param' field"+ assert "code" in error2, "Error should have 'code' field"+ assert error2["type"] == "bad_request"+ assert error2["code"] == "400"+ assert "Customer already exists" in error2["message"]++ # Verify both errors have the same schema structure+ assert set(error1.keys()) == set(error2.keys()), \+ "Both errors should have the same top-level keys"++ # Both should have string values for all fields+ for key in ["message", "type", "code"]:+ assert isinstance(error1[key], str), f"error1[{key}] should be a string"+ assert isinstance(error2[key], str), f"error2[{key}] should be a string"