Skip to content

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]

Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_fix_batch_group_fallback

mateo-berri933c18b21c8c
diff --cc litellm/router_utils/fallback_event_handlers.py
index 00df20be845,ef48ccc821e..928845d1ff2
--- a/litellm/router_utils/fallback_event_handlers.py
+++ b/litellm/router_utils/fallback_event_handlers.py
@@@ -1,3 -1,6 +1,7 @@@
+ import hashlib
+ import json
++from collections.abc import Mapping
+ from dataclasses import dataclass
from enum import Enum
from typing import TYPE_CHECKING, Any, Final
@@@ -83,28 -131,6 +133,28 @@@ def get_fallback_model_group(fallbacks
return fallback_model_group, generic_fallback_idx
+PROVIDER_SCOPED_RESOURCE_KEYS: Final = ("input_file_id", "training_file")
+
+
- def _get_fallback_target_model_group(fallback_entry: str | dict[str, object]) -> str | None:
++def _get_fallback_target_model_group(fallback_entry: str | Mapping[str, object]) -> str | None:
+ if isinstance(fallback_entry, str):
+ return fallback_entry
+ target: Final = fallback_entry.get("model")
+ return target if isinstance(target, str) else None
+
+
- def references_provider_scoped_resource(kwargs: dict[str, object]) -> bool:
++def references_provider_scoped_resource(kwargs: Mapping[str, object]) -> bool:
+ """
+ True when the request names a file that only exists under one provider's credentials.
+
+ Batch and fine-tuning jobs are created from a file the caller already uploaded, and
+ that file lives in the account of the deployment that stored it. Handing the id to a
+ different model group can only fail, and the second provider's error replaces the
+ error the caller actually needs to see.
+ """
+ return any(kwargs.get(key) for key in PROVIDER_SCOPED_RESOURCE_KEYS)
+
+
async def run_async_fallback(
*args: tuple[Any],
litellm_router: LitellmRouter,
@@@ -143,21 -176,27 +200,38 @@@
error_from_fallbacks = original_exception
fallback_errors = (get_fallback_error_info(original_exception),)
+ metadata_variable_name: Final = _get_router_metadata_variable_name(
+ function_name=getattr(kwargs.get("original_function"), "__name__", None)
+ )
+ same_model_group_only: Final = references_provider_scoped_resource(kwargs)
+ # Read out of kwargs and narrowed here rather than declared as a parameter: every caller
+ # reaches this function by spreading a loosely-typed kwargs dict, so a declared parameter
+ # would carry an annotation that no call site can actually be checked against.
+ carried_targets: Final = kwargs.get("attempted_targets")
+ attempted: Final = (
+ carried_targets if isinstance(carried_targets, AttemptedFallbackTargets) else AttemptedFallbackTargets()
+ )
+ attempted.record(original_model_group)
for mg in fallback_model_group:
if mg == original_model_group:
continue
+ if same_model_group_only and _get_fallback_target_model_group(mg) != original_model_group:
+ verbose_router_logger.info(
+ "Skipping fallback to model_group = %s: request is pinned to model_group = %s by its uploaded file",
+ mask_sensitive_structure(mg),
+ original_model_group,
+ )
+ continue
+ attempt_key = fallback_attempt_key(mg)
+ if attempt_key is not None:
+ if attempt_key in attempted:
+ verbose_router_logger.info(
+ "Skipping fallback to model_group = %s, already attempted for this request",
+ mask_sensitive_structure(mg),
+ )
+ continue
+ attempted.record(attempt_key)
try:
# LOGGING
kwargs = litellm_router.log_retry(kwargs=kwargs, e=original_exception)
diff --cc tests/test_litellm/router_utils/test_fallback_event_handlers.py
index d93aa4ab023,e2348d28701..f572b68135f
--- a/tests/test_litellm/router_utils/test_fallback_event_handlers.py
+++ b/tests/test_litellm/router_utils/test_fallback_event_handlers.py
@@@ -142,147 -144,208 +144,349 @@@ async def test_run_async_fallback_skips
assert response._hidden_params["additional_headers"]["x-litellm-attempted-fallbacks"] == 1
+class AttemptRecordingRouter:
+ def __init__(self):
+ self.attempted_model_groups = []
+ self.received_kwargs = None
+
+ def log_retry(self, kwargs, e):
+ return kwargs
+
+ async def async_function_with_fallbacks(self, *args, **kwargs):
+ self.attempted_model_groups.append(kwargs.get("model"))
+ self.received_kwargs = kwargs
+ return StreamingWrapper()
+
+
+async def _acreate_batch(*args, **kwargs):
+ raise AssertionError("only used for its __name__")
+
+
+async def test_run_async_fallback_keeps_uploaded_file_requests_in_their_model_group():
+ """An input_file_id only exists under the credentials of the group it was uploaded
+ to, so a cross-group fallback can only fail with the wrong provider's error."""
+ router = AttemptRecordingRouter()
+ owning_provider_error = RuntimeError("openai connection error")
+
+ with pytest.raises(RuntimeError, match="openai connection error"):
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=["azure-group"],
+ original_model_group="openai-group",
+ original_exception=owning_provider_error,
+ max_fallbacks=3,
+ fallback_depth=0,
+ model="openai-group",
+ input_file_id="file-owned-by-openai",
+ original_function=_acreate_batch,
+ )
+
+ assert router.attempted_model_groups == []
+
+
+async def test_run_async_fallback_keeps_fine_tuning_requests_in_their_model_group():
+ router = AttemptRecordingRouter()
+
+ with pytest.raises(RuntimeError, match="openai connection error"):
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=["azure-group"],
+ original_model_group="openai-group",
+ original_exception=RuntimeError("openai connection error"),
+ max_fallbacks=3,
+ fallback_depth=0,
+ model="openai-group",
+ training_file="file-owned-by-openai",
+ )
+
+ assert router.attempted_model_groups == []
+
+
+async def test_run_async_fallback_allows_same_model_group_retry_for_uploaded_file_requests():
+ """Order-based fallbacks stay inside the owning group, so they must still run."""
+ router = AttemptRecordingRouter()
+
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=[{"model": "openai-group", "_target_order": 2}],
+ original_model_group="openai-group",
+ original_exception=RuntimeError("first deployment failed"),
+ max_fallbacks=3,
+ fallback_depth=0,
+ model="openai-group",
+ input_file_id="file-owned-by-openai",
+ original_function=_acreate_batch,
+ )
+
+ assert router.attempted_model_groups == ["openai-group"]
+
+
+async def test_run_async_fallback_still_crosses_model_groups_without_an_uploaded_file():
+ router = AttemptRecordingRouter()
+
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=["azure-group"],
+ original_model_group="openai-group",
+ original_exception=RuntimeError("openai connection error"),
+ max_fallbacks=3,
+ fallback_depth=0,
+ model="openai-group",
+ )
+
+ assert router.attempted_model_groups == ["azure-group"]
+
+
+async def test_run_async_fallback_handles_explicitly_none_metadata():
+ """/v1/batches always sets `metadata`, and sets it to None when the caller sent
+ none, so setdefault() on it hands back None instead of a dict."""
+ router = AttemptRecordingRouter()
+
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=["azure-group"],
+ original_model_group="openai-group",
+ original_exception=RuntimeError("openai connection error"),
+ max_fallbacks=3,
+ fallback_depth=0,
+ model="openai-group",
+ metadata=None,
+ )
+
+ assert router.received_kwargs["metadata"] == {"model_group": "azure-group"}
+
+
+async def test_run_async_fallback_records_batch_model_group_outside_provider_metadata():
+ """`metadata` on a batch request is forwarded to the provider and stored on the
+ batch, so the router's own model_group belongs in litellm_metadata."""
+ router = AttemptRecordingRouter()
+
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=[{"model": "openai-group", "_target_order": 2}],
+ original_model_group="openai-group",
+ original_exception=RuntimeError("first deployment failed"),
+ max_fallbacks=3,
+ fallback_depth=0,
+ model="openai-group",
+ input_file_id="file-owned-by-openai",
+ metadata={"caller": "nightly-job"},
+ litellm_metadata={"model_group": "openai-group"},
+ original_function=_acreate_batch,
+ )
+
+ assert router.received_kwargs["metadata"] == {"caller": "nightly-job"}
+ assert router.received_kwargs["litellm_metadata"]["model_group"] == "openai-group"
+
+
+ class RecordingFailRouter:
+ def __init__(self):
+ self.attempted_models = []
+
+ def log_retry(self, kwargs, e):
+ return kwargs
+
+ async def async_function_with_fallbacks(self, *args, **kwargs):
+ self.attempted_models.append(kwargs.get("model"))
+ raise RuntimeError("fallback model also failed")
+
+
+ @pytest.mark.asyncio
+ async def test_run_async_fallback_skips_model_group_already_attempted():
+ """A fallback graph that loops back on itself must not re-attempt a model group that
+ already failed for this request. Every group in a cycle fails identically, so
+ revisiting one multiplies the work and the error output without any chance of
+ succeeding."""
+ router = RecordingFailRouter()
+
+ with pytest.raises(RuntimeError, match="original failed"):
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=["already-attempted"],
+ original_model_group="primary-model",
+ original_exception=RuntimeError("original failed"),
+ max_fallbacks=3,
+ fallback_depth=0,
+ attempted_targets=AttemptedFallbackTargets(frozenset({"already-attempted"})),
+ )
+
+ assert router.attempted_models == []
+
+
+ @pytest.mark.asyncio
+ async def test_run_async_fallback_attempts_a_repeated_target_once():
+ router = RecordingFailRouter()
+
+ with pytest.raises(RuntimeError, match="fallback model also failed"):
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=["fallback-model", "fallback-model", "other-model"],
+ original_model_group="primary-model",
+ original_exception=RuntimeError("original failed"),
+ max_fallbacks=5,
+ fallback_depth=0,
+ )
+
+ assert router.attempted_models == ["fallback-model", "other-model"]
+
+
+ @pytest.mark.asyncio
+ async def test_run_async_fallback_forwards_attempted_model_groups_to_nested_call():
+ """The nested call is where the next hop of the walk decides what to skip, so the
+ accumulated set has to reach it, carrying both the group that just failed and the
+ target being attempted."""
+ router = RecordingRouter()
+
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=["fallback-model"],
+ original_model_group="primary-model",
+ original_exception=RuntimeError("original failed"),
+ max_fallbacks=3,
+ fallback_depth=0,
+ attempted_targets=AttemptedFallbackTargets(frozenset({"earlier-model"})),
+ )
+
+ assert router.received_kwargs["attempted_targets"].keys == frozenset(
+ {"earlier-model", "primary-model", "fallback-model"}
+ )
+
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "entry",
+ [
+ {"model": "primary-model", "_target_order": 2},
+ {"model": "primary-model", "_excluded_deployment_ids": ["dep-1"]},
+ ],
+ )
+ async def test_run_async_fallback_still_retargets_the_same_group_via_dict_entry(entry):
+ """Order-based fallback and weighted intra-group failover both re-target the group that
+ just failed, selecting a different set of deployments inside it. Those entries are dicts
+ rather than plain names and must survive a guard that skips already-attempted names."""
+ router = RecordingRouter()
+
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=[entry],
+ original_model_group="primary-model",
+ original_exception=RuntimeError("original failed"),
+ max_fallbacks=3,
+ fallback_depth=0,
+ attempted_targets=AttemptedFallbackTargets(frozenset({"primary-model"})),
+ )
+
+ assert router.received_kwargs["model"] == "primary-model"
+
+
+ @pytest.mark.asyncio
+ async def test_run_async_fallback_skips_a_repeated_dict_target():
+ """A client-side fallback list names its targets with dicts, and that list is re-walked
+ at every level of the recursion, so an entry that carries no request override has to be
+ recognised as the same attempt as the bare name."""
+ router = RecordingFailRouter()
+
+ with pytest.raises(RuntimeError, match="original failed"):
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=[{"model": "already-attempted"}],
+ original_model_group="primary-model",
+ original_exception=RuntimeError("original failed"),
+ max_fallbacks=3,
+ fallback_depth=0,
+ attempted_targets=AttemptedFallbackTargets(frozenset({"already-attempted"})),
+ )
+
+ assert router.attempted_models == []
+
+
+ @pytest.mark.asyncio
+ async def test_run_async_fallback_attempts_a_repeated_dict_target_once():
+ router = RecordingFailRouter()
+ entry = {"model": "fallback-model", "messages": [{"role": "user", "content": "shorter"}]}
+
+ with pytest.raises(RuntimeError, match="fallback model also failed"):
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=[entry, entry, {"model": "other-model"}],
+ original_model_group="primary-model",
+ original_exception=RuntimeError("original failed"),
+ max_fallbacks=5,
+ fallback_depth=0,
+ )
+
+ assert router.attempted_models == ["fallback-model", "other-model"]
+
+
+ @pytest.mark.asyncio
+ async def test_run_async_fallback_keeps_a_request_override_distinct_from_the_bare_name():
+ """The documented use of the client-side form is to retry a group with different request
+ params, so an entry carrying an override must survive even when the bare name of that
+ same group has already been attempted."""
+ router = RecordingFailRouter()
+
+ with pytest.raises(RuntimeError, match="fallback model also failed"):
+ await run_async_fallback(
+ litellm_router=router,
+ fallback_model_group=[
+ {"model": "already-attempted", "messages": [{"role": "user", "content": "shorter"}]}
+ ],
+ original_model_group="primary-model",
+ original_exception=RuntimeError("original failed"),
+ max_fallbacks=3,
+ fallback_depth=0,
+ attempted_targets=AttemptedFallbackTargets(frozenset({"already-attempted"})),
+ )
+
+ assert router.attempted_models == ["already-attempted"]
+
+
+ @pytest.mark.parametrize(
+ "target, expected",
+ [
+ ("group-a", "group-a"),
+ ({"model": "group-a"}, "group-a"),
+ (None, None),
+ (["group-a"], None),
+ ],
+ )
+ def test_fallback_attempt_key_identity(target, expected):
+ """A bare name and a `{"model": name}` entry are the same attempt. A shape with no
+ usable identity returns None and is never skipped, so an unrecognised entry keeps
+ today's behaviour rather than being silently dropped."""
+ assert fallback_attempt_key(target) == expected
+
+
+ def test_fallback_attempt_key_gives_a_param_only_entry_its_own_identity():
+ """An entry with no `model` re-targets the group currently being attempted with
+ different request params, so it is a distinct attempt and still needs an identity."""
+ key = fallback_attempt_key({"messages": [{"role": "user", "content": "shorter"}]})
+
+ assert key is not None
+ assert key != fallback_attempt_key({"messages": [{"role": "user", "content": "other"}]})
+
+
+ def test_fallback_attempt_key_separates_overrides_from_the_bare_name():
+ bare = fallback_attempt_key("group-a")
+ override = fallback_attempt_key({"model": "group-a", "messages": [{"role": "user", "content": "x"}]})
+ other_override = fallback_attempt_key({"model": "group-a", "messages": [{"role": "user", "content": "y"}]})
+ order_retarget = fallback_attempt_key({"model": "group-a", "_target_order": 2})
+
+ assert len({bare, override, other_override, order_retarget}) == 4
+
+
+ def test_fallback_attempt_key_is_stable_across_key_order():
+ assert fallback_attempt_key({"model": "group-a", "_target_order": 2}) == fallback_attempt_key(
+ {"_target_order": 2, "model": "group-a"}
+ )
+
+
def test_get_fallback_model_group_does_not_mutate_fallbacks():
"""A string fallback must be resolved without mutating the caller's
fallbacks list, which is the live router config shared across requests."""