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
Allow forwarding clientside headers by model group (#12753)
Krish Dholakiaa89a49f1e118
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex 386d10e4e71..99a5454ace4 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -280,6 +280,7 @@ default_redis_ttl: Optional[float] = Nonedefault_redis_batch_cache_expiry: Optional[float] = Nonemodel_alias_map: Dict[str, str] = {}model_group_alias_map: Dict[str, str] = {}+model_group_settings: Optional["ModelGroupSettings"] = Nonemax_budget: float = 0.0 # set the max budget across all providersbudget_duration: Optional[str] = (None # proxy only - resets budget after fixed duration. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d").diff --git a/litellm/litellm_core_utils/logging_callback_manager.py b/litellm/litellm_core_utils/logging_callback_manager.pyindex ab6c2ac7659..44cb146f91a 100644--- a/litellm/litellm_core_utils/logging_callback_manager.py+++ b/litellm/litellm_core_utils/logging_callback_manager.py@@ -87,16 +87,21 @@ class LoggingCallbackManager:callback=callback, parent_list=litellm._async_failure_callback)- def remove_callback_from_list_by_object(self, callback_list, obj):+ def remove_callback_from_list_by_object(+ self, callback_list, obj, require_self=True+ ):"""Remove callbacks that are methods of a particular object (e.g., router cleanup)"""if not isinstance(callback_list, list): # Not list -> do nothingreturn- remove_list = [- c for c in callback_list if hasattr(c, "__self__") and c.__self__ == obj- ]+ if require_self:+ remove_list = [+ c for c in callback_list if hasattr(c, "__self__") and c.__self__ == obj+ ]+ else:+ remove_list = [c for c in callback_list if c == obj]for c in remove_list:callback_list.remove(c)@@ -280,61 +285,61 @@ class LoggingCallbackManager:def get_callbacks_by_type(self) -> CallbacksByType:"""Get all active callbacks categorized by their type (success, failure, success_and_failure).-+Returns:CallbacksByType: Dict with keys 'success', 'failure', 'success_and_failure' containing lists of callback strings"""# Get callback lists- success_callbacks = set(litellm.success_callback + litellm._async_success_callback)- failure_callbacks = set(litellm.failure_callback + litellm._async_failure_callback)+ success_callbacks = set(+ litellm.success_callback + litellm._async_success_callback+ )+ failure_callbacks = set(+ litellm.failure_callback + litellm._async_failure_callback+ )general_callbacks = set(litellm.callbacks)-+# Get all unique callbacksall_callbacks = success_callbacks | failure_callbacks | general_callbacks-+result: CallbacksByType = CallbacksByType(- success=[],- failure=[],- success_and_failure=[]+ success=[], failure=[], success_and_failure=[])-+for callback in all_callbacks:callback_str = self._get_callback_string(callback)-+is_in_success = callback in success_callbacksis_in_failure = callback in failure_callbacksis_in_general = callback in general_callbacks-+if is_in_general or (is_in_success and is_in_failure):result["success_and_failure"].append(callback_str)elif is_in_success:result["success"].append(callback_str)elif is_in_failure:result["failure"].append(callback_str)--# final de-duplicationresult["success"] = list(set(result["success"]))result["failure"] = list(set(result["failure"]))result["success_and_failure"] = list(set(result["success_and_failure"]))-+return result-- def _get_callback_string(- self,- callback: Union[CustomLogger, Callable, str]- ) -> str:++ def _get_callback_string(self, callback: Union[CustomLogger, Callable, str]) -> str:from litellm.litellm_core_utils.custom_logger_registry import (CustomLoggerRegistry,)+"""Convert a callback to its string representation"""if isinstance(callback, str):return callbackelif isinstance(callback, CustomLogger):# Try to get the string representation from the registry- callback_str = CustomLoggerRegistry.get_callback_str_from_class_type(type(callback))+ callback_str = CustomLoggerRegistry.get_callback_str_from_class_type(+ type(callback)+ )return callback_str if callback_str is not None else type(callback).__name__elif callable(callback):- return getattr(callback, '__name__', str(callback))+ return getattr(callback, "__name__", str(callback))return str(callback)diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yamlindex 4f9a633acae..054491ba415 100644--- a/litellm/proxy/_new_secret_config.yaml+++ b/litellm/proxy/_new_secret_config.yaml@@ -1,13 +1,24 @@model_list:- - model_name: openai/gpt-3.5-turbo+ - model_name: gpt-3.5-turbo-allowlitellm_params:- model: openai/gpt-3.5-turbo+ model: gpt-3.5-turbomodel_info:version: 2+ - model_name: gpt-3.5-turbo-disallow+ litellm_params:+ model: gpt-3.5-turbo+ model_info:+ version: 2+ - model_name: openai/*+ litellm_params:+ model: openai/*+ - model_name: openai/gpt-4o-mini+ litellm_params:+ model: openai/gpt-4o-mini-router_settings:- model_group_alias: {"gemini-2.5-pro": "openai/gpt-3.5-turbo"}--# Tried adding the below settings as welllitellm_settings:- stream: false\ No newline at end of file+ model_group_alias: {"gpt-3.5-turbo-custom": "gpt-3.5-turbo-disallow"}+ model_group_settings:+ forward_client_headers_to_llm_api:+ - "gpt-3.5-turbo-allow"+ - "openai/*"diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.pyindex f4a7b30126f..d0dd025309f 100644--- a/litellm/proxy/litellm_pre_call_utils.py+++ b/litellm/proxy/litellm_pre_call_utils.py@@ -563,6 +563,7 @@ async def add_litellm_data_to_request( # noqa: PLR0915"""from litellm.proxy.proxy_server import llm_router, premium_user+ from litellm.types.proxy.litellm_pre_call_utils import SecretFieldssafe_add_api_version_from_query_params(data, request)@@ -599,6 +600,8 @@ async def add_litellm_data_to_request( # noqa: PLR0915"body": copy.copy(data), # use copy instead of deepcopy}+ data["secret_fields"] = SecretFields(raw_headers=dict(request.headers))+## Dynamic api version (Azure OpenAI endpoints) ##try:query_params = request.query_paramsdiff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex d2424b9ed51..50a044d9835 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -1807,6 +1807,11 @@ class ProxyConfig:litellm_settings=litellm_settings,)+ elif key == "model_group_settings":+ from litellm.types.router import ModelGroupSettings++ litellm.model_group_settings = ModelGroupSettings(**value)+elif key == "post_call_rules":litellm.post_call_rules = [get_instance_fn(value=value, config_file_path=config_file_path)diff --git a/litellm/router.py b/litellm/router.pyindex 644422cda34..8eeb6e24170 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -92,6 +92,9 @@ from litellm.router_utils.fallback_event_handlers import (get_fallback_model_group,run_async_fallback,)+from litellm.router_utils.forward_clientside_headers_by_model_group import (+ ForwardClientSideHeadersByModelGroup,+)from litellm.router_utils.get_retry_from_policy import (get_num_retries_from_retry_policy as _get_num_retries_from_retry_policy,)@@ -178,6 +181,7 @@ class Router:tenacity = Noneleastbusy_logger: Optional[LeastBusyLoggingHandler] = Nonelowesttpm_logger: Optional[LowestTPMLoggingHandler] = None+ optional_callbacks: Optional[List[Union[CustomLogger, Callable, str]]] = Nonedef __init__( # noqa: PLR0915self,@@ -601,6 +605,18 @@ class Router:self.initialize_assistants_endpoint()self.initialize_router_endpoints()+ self.apply_default_settings()++ def apply_default_settings(self):+ """+ Apply the default settings to the router.+ """++ default_pre_call_checks: OptionalPreCallChecks = [+ "forward_client_headers_by_model_group",+ ]+ self.add_optional_pre_call_checks(default_pre_call_checks)+ return Nonedef discard(self):"""@@ -629,6 +645,13 @@ class Router:litellm.callbacks, self)+ # Remove ForwardClientSideHeadersByModelGroup if it exists+ if self.optional_callbacks is not None:+ for callback in self.optional_callbacks:+ litellm.logging_callback_manager.remove_callback_from_list_by_object(+ litellm.callbacks, callback, require_self=False+ )+@staticmethoddef _create_redis_cache(cache_config: Dict[str, Any],@@ -843,6 +866,7 @@ class Router:def add_optional_pre_call_checks(self, optional_pre_call_checks: Optional[OptionalPreCallChecks]):+if optional_pre_call_checks is not None:for pre_call_check in optional_pre_call_checks:_callback: Optional[CustomLogger] = None@@ -856,7 +880,12 @@ class Router:)elif pre_call_check == "responses_api_deployment_check":_callback = ResponsesApiDeploymentCheck()+ elif pre_call_check == "forward_client_headers_by_model_group":+ _callback = ForwardClientSideHeadersByModelGroup()if _callback is not None:+ if self.optional_callbacks is None:+ self.optional_callbacks = []+ self.optional_callbacks.append(_callback)litellm.logging_callback_manager.add_litellm_callback(_callback)def print_deployment(self, deployment: dict):@@ -1194,7 +1223,12 @@ class Router:"""kwargs["num_retries"] = kwargs.get("num_retries", self.num_retries)kwargs.setdefault("litellm_trace_id", str(uuid.uuid4()))- kwargs.setdefault(metadata_variable_name, {}).update({"model_group": model})+ model_group_alias: Optional[str] = None+ if self._get_model_from_alias(model=model):+ model_group_alias = model+ kwargs.setdefault(metadata_variable_name, {}).update(+ {"model_group": model, "model_group_alias": model_group_alias}+ )def _update_kwargs_with_default_litellm_params(self, kwargs: dict, metadata_variable_name: Optional[str] = "metadata"@@ -1258,14 +1292,15 @@ class Router:- Adds default litellm params to kwargs, if set."""model_info = deployment.get("model_info", {}).copy()- deployment_model_name = deployment["litellm_params"]["model"]+ deployment_litellm_model_name = deployment["litellm_params"]["model"]deployment_api_base = deployment["litellm_params"].get("api_base")+ deployment_model_name = deployment["model_name"]if is_clientside_credential(request_kwargs=kwargs):deployment_pydantic_obj = self._handle_clientside_credential(deployment=deployment, kwargs=kwargs)model_info = deployment_pydantic_obj.model_info.model_dump()- deployment_model_name = deployment_pydantic_obj.litellm_params.model+ deployment_litellm_model_name = deployment_pydantic_obj.litellm_params.modeldeployment_api_base = deployment_pydantic_obj.litellm_params.api_basemetadata_variable_name = _get_router_metadata_variable_name(@@ -1274,9 +1309,10 @@ class Router:kwargs.setdefault(metadata_variable_name, {}).update({- "deployment": deployment_model_name,+ "deployment": deployment_litellm_model_name,"model_info": model_info,"api_base": deployment_api_base,+ "deployment_model_name": deployment_model_name,})kwargs["model_info"] = model_info@@ -3325,7 +3361,13 @@ class Router:- An asynchronous function for asynchronous call types"""# Handle synchronous call types- if call_type in ("responses", "generate_content", "generate_content_stream", "vector_store_search", "vector_store_create"):+ if call_type in (+ "responses",+ "generate_content",+ "generate_content_stream",+ "vector_store_search",+ "vector_store_create",+ ):def sync_wrapper(custom_llm_provider: Optional[diff --git a/litellm/router_utils/forward_clientside_headers_by_model_group.py b/litellm/router_utils/forward_clientside_headers_by_model_group.pynew file mode 100644index 00000000000..87c2e48f689--- /dev/null+++ b/litellm/router_utils/forward_clientside_headers_by_model_group.py@@ -0,0 +1,72 @@+from typing import Any, Dict, Optional, TypedDict++from litellm.types.utils import CallTypes++from ..integrations.custom_logger import CustomLogger+++class PotentialModelGroups(TypedDict):+ deployment_model_name: Optional[str]+ model_group_alias: Optional[str]+++class ForwardClientSideHeadersByModelGroup(CustomLogger):+ def get_potential_model_groups_from_kwargs(+ self, kwargs: Dict[str, Any]+ ) -> Optional[PotentialModelGroups]:+ """+ Get the model group from the kwargs.++ Returns the potential model groups from the kwargs.+ - deployment_model_name (useful for wildcard model names)+ - model_group_alias (if the model is an alias)+ """+ metadata = kwargs.get("litellm_metadata") or kwargs.get("metadata")+ if metadata is None:+ return None+ deployment_model_name = metadata.get("deployment_model_name", None)+ model_group_alias = metadata.get("model_group_alias", None)+ return {+ "deployment_model_name": deployment_model_name,+ "model_group_alias": model_group_alias,+ }++ async def async_pre_call_deployment_hook(+ self, kwargs: Dict[str, Any], call_type: Optional[CallTypes]+ ) -> Optional[dict]:+ """+ if kwargs["proxy_server_request"]["headers"] is not None:+ and kwargs["forward_client_headers_to_llm_api"] is not None:++ add the headers to the request+ kwargs["headers"].update(kwargs["proxy_server_request"]["headers"])+ """+ import litellm++ if litellm.model_group_settings is None:+ return None++ potential_model_groups = self.get_potential_model_groups_from_kwargs(kwargs)++ if potential_model_groups is None:+ return None++ if (+ "secret_fields" in kwargs+ and kwargs["secret_fields"]["raw_headers"] is not None+ and isinstance(kwargs["secret_fields"]["raw_headers"], dict)+ ):+ for model_group in potential_model_groups.values():+ if model_group is None:+ continue+ if (+ litellm.model_group_settings.forward_client_headers_to_llm_api+ is not None+ and model_group+ in litellm.model_group_settings.forward_client_headers_to_llm_api+ ):+ kwargs.setdefault("headers", {}).update(+ kwargs["secret_fields"]["raw_headers"]+ )++ return kwargsdiff --git a/litellm/types/proxy/litellm_pre_call_utils.py b/litellm/types/proxy/litellm_pre_call_utils.pynew file mode 100644index 00000000000..c33f1ba8bce--- /dev/null+++ b/litellm/types/proxy/litellm_pre_call_utils.py@@ -0,0 +1,11 @@+from typing import TypedDict+++class SecretFields(TypedDict):+ """+ Stored in data["secret_fields"]++ these fields are not logged, but used for internal purposes.+ """++ raw_headers: dictdiff --git a/litellm/types/router.py b/litellm/types/router.pyindex fb964bb557b..02647c543a7 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -722,7 +722,10 @@ class GenericBudgetWindowDetails(BaseModel):OptionalPreCallChecks = List[Literal[- "prompt_caching", "router_budget_limiting", "responses_api_deployment_check"+ "prompt_caching",+ "router_budget_limiting",+ "responses_api_deployment_check",+ "forward_client_headers_by_model_group",]]@@ -759,3 +762,7 @@ class MockRouterTestingParams:"mock_testing_content_policy_fallbacks"),)+++class ModelGroupSettings(BaseModel):+ forward_client_headers_to_llm_api: Optional[List[str]] = Nonediff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 0f803cb8c50..5ff17bd3378 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -2145,6 +2145,7 @@ all_litellm_params = ["hf_model_name","model_info","proxy_server_request",+ "secret_fields","preset_cache_key","caching_groups","ttl",@@ -2317,6 +2318,7 @@ class LlmProviders(str, Enum):# Create a set of all provider values for quick lookupLlmProvidersSet = {provider.value for provider in LlmProviders}+class LiteLLMLoggingBaseClass:"""Base class for logging pre and post calldiff --git a/litellm/utils.py b/litellm/utils.pyindex ef26c8bd764..e91c626dcb2 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -902,7 +902,9 @@ def client(original_function): # noqa: PLR0915typed_call_type = None # unknown call typemodified_kwargs = kwargs.copy()+for callback in litellm.callbacks:+if isinstance(callback, CustomLogger):result = await callback.async_pre_call_deployment_hook(modified_kwargs, typed_call_type@@ -1332,6 +1334,7 @@ def client(original_function): # noqa: PLR0915logging_obj, kwargs = function_setup(original_function.__name__, rules_obj, start_time, *args, **kwargs)+modified_kwargs = await async_pre_call_deployment_hook(kwargs, call_type)if modified_kwargs is not None:kwargs = modified_kwargsdiff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.pyindex e7201723df3..638dfd774bf 100644--- a/tests/test_litellm/test_router.py+++ b/tests/test_litellm/test_router.py@@ -661,7 +661,6 @@ def test_arouter_responses_api_bridge():assert mock_post.call_args.kwargs["json"]["model"] == "webinterface-o3-pro"-@pytest.mark.asyncioasync def test_router_v1_messages_fallbacks():"""@@ -699,17 +698,17 @@ async def test_router_v1_messages_fallbacks():print(result)assert result["content"][0]["text"] == "Hello, world I am a fallback!"-+def test_add_invalid_provider_to_router():"""Test that router.add_deployment raises an error if the provider is invalid"""from litellm.types.router import Deployment-+router = litellm.Router(model_list=[{- "model_name": "gpt-3.5-turbo",+ "model_name": "gpt-3.5-turbo","litellm_params": {"model": "gpt-3.5-turbo"},}],@@ -728,6 +727,7 @@ def test_add_invalid_provider_to_router():assert router.pattern_router.patterns == {}+@pytest.mark.asyncioasync def test_router_ageneric_api_call_with_fallbacks_helper():"""@@ -892,4 +892,146 @@ async def test_router_ageneric_api_call_with_fallbacks_helper():assert "Mock failure" in str(exc_info.value)# Check that fail_calls was incremented- assert router.fail_calls["gpt-3.5-turbo"] == initial_fail_count + 1\ No newline at end of file+ assert router.fail_calls["gpt-3.5-turbo"] == initial_fail_count + 1+++async def test_router_forward_client_headers_by_model_group():+ """+ Test that router.forward_client_headers_by_model_group returns the correct response+ """+ from unittest.mock import MagicMock, patch++ from litellm.types.router import ModelGroupSettings++ litellm.model_group_settings = ModelGroupSettings(+ forward_client_headers_to_llm_api=[+ "gpt-3.5-turbo-allow",+ "openai/*",+ "gpt-3.5-turbo-custom",+ ]+ )++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo-allow",+ "litellm_params": {+ "model": "gpt-3.5-turbo",+ },+ },+ {+ "model_name": "gpt-3.5-turbo-disallow",+ "litellm_params": {+ "model": "gpt-3.5-turbo",+ },+ },+ {+ "model_name": "openai/*",+ "litellm_params": {+ "model": "openai/*",+ },+ },+ {+ "model_name": "openai/gpt-4o-mini",+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ },+ },+ ],+ model_group_alias={+ "gpt-3.5-turbo-custom": "gpt-3.5-turbo-disallow",+ },+ )++ ## Scenario 1: Direct model name+ with patch.object(+ litellm.main, "completion", return_value=MagicMock()+ ) as mock_completion:+ await router.acompletion(+ model="gpt-3.5-turbo-allow",+ messages=[{"role": "user", "content": "Hello, world!"}],+ mock_response="Hello, world!",+ secret_fields={"raw_headers": {"test": "test"}},+ )++ mock_completion.assert_called_once()+ print(mock_completion.call_args.kwargs["headers"])++ ## Scenario 2: Wildcard model name+ with patch.object(+ litellm.main, "completion", return_value=MagicMock()+ ) as mock_completion:+ await router.acompletion(+ model="openai/gpt-3.5-turbo",+ messages=[{"role": "user", "content": "Hello, world!"}],+ mock_response="Hello, world!",+ secret_fields={"raw_headers": {"test": "test"}},+ )++ mock_completion.assert_called_once()+ print(mock_completion.call_args.kwargs["headers"])++ ## Scenario 3: Not in model_group_settings+ with patch.object(+ litellm.main, "completion", return_value=MagicMock()+ ) as mock_completion:+ await router.acompletion(+ model="openai/gpt-4o-mini",+ messages=[{"role": "user", "content": "Hello, world!"}],+ mock_response="Hello, world!",+ secret_fields={"raw_headers": {"test": "test"}},+ )++ mock_completion.assert_called_once()+ assert mock_completion.call_args.kwargs.get("headers") is None++ ## Scenario 4: Model group alias+ with patch.object(+ litellm.main, "completion", return_value=MagicMock()+ ) as mock_completion:+ await router.acompletion(+ model="gpt-3.5-turbo-custom",+ messages=[{"role": "user", "content": "Hello, world!"}],+ mock_response="Hello, world!",+ secret_fields={"raw_headers": {"test": "test"}},+ )++ mock_completion.assert_called_once()+ print(mock_completion.call_args.kwargs["headers"])+++def test_router_apply_default_settings():+ """+ Test that Router.apply_default_settings() adds the expected default pre-call checks+ """+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {"model": "gpt-3.5-turbo"},+ }+ ],+ )++ # Apply default settings+ result = router.apply_default_settings()++ # Verify the method returns None+ assert result is None++ # Verify that the forward_client_headers_by_model_group pre-call check was added+ # Check if any callback is of the ForwardClientHeadersByModelGroupCheck type+ has_forward_headers_check = False+ for callback in litellm.callbacks:+ print(callback)+ print(f"callback.__class__: {callback.__class__}")+ if hasattr(+ callback, "__class__"+ ) and "ForwardClientSideHeadersByModelGroup" in str(callback.__class__):+ has_forward_headers_check = True+ break++ assert (+ has_forward_headers_check+ ), "Expected ForwardClientSideHeadersByModelGroup to be added to callbacks"