litellm/litellm/router_utils/cooldown_handlers.py
giladk1221 9d827093c5
feat(github_copilot): support GitHub App authentication with PEM upload (#51427)
* feat(github_copilot): support GitHub App installation authentication

* Add GitHub App authentication to the Copilot credential form

* Explain secure private-key setup beside Copilot App fields

* Store uploaded Copilot App keys through encrypted named credentials

* fix(github_copilot): handle App validation errors and credential replacement

* fix(ui): make GitHub App field help accessible

* fix(github_copilot): preserve saved App key references on edit

* fix(github_copilot): trust litellm's CA settings when minting App tokens and hide App keys from /health

* fix(github_copilot): keep device-login headers, mint App tokens off the shared thread pool, cache App responses

Device-login requests keep the merge base header behavior, so caller headers still replace the Copilot defaults. Only App requests merge and pin their identity headers.

App token refreshes are single-flight per cache key with a shared future. Only the refreshing caller uses a thread, so waiting callers no longer fill the default executor that every provider call shares.

A cached App token is served before the key secret is read. Uploaded keys still rotate the token when their contents change.

App deployments are deployment-owned, so they share the response cache like shared device-login deployments.

App credentials are validated even when credential_info names no provider.

* fix(github_copilot): finish an App token refresh even when the caller that started it is cancelled

The caller that owns a refresh used to await asyncio.to_thread, so cancelling it while the job was still queued cancelled the job, left the in-flight future unfinished, and every later request for that App waited on it. The refresh now runs in the executor without being tied to the caller, and every caller, the owner included, awaits the shared future

* fix(github_copilot): refuse deployments naming an unloaded credential, keep App key references, accept numeric App IDs

A Copilot deployment whose litellm_credential_name is not loaded now answers 400 instead of falling back to the shared device login. The router registry keeps github_copilot_app_private_key_ref values as references, a YAML App ID can be an integer, the server-owned field error names Copilot auth for Copilot fields, and the credential edit modal shows the stored provider again

* fix(github_copilot): report a deployment naming an unloaded credential as unhealthy

The /health check now answers unhealthy with the same 400 the request path returns for a Copilot deployment whose litellm_credential_name is not loaded, instead of running it through the shared device login

* fix(github_copilot): keep the base fallback for an unloaded credential and report the App host as api_base

A Copilot deployment that names an unloaded credential uses the shared device login again, as on base.
A deployment that sets github_copilot_auth_type: github_app still refuses before any GitHub call.
get_api_base now returns the Copilot host an App or per-user session calls instead of an admin api_base it ignores.

* fix(github_copilot): count a GitHub rejection of the App installation token as a Prometheus deployment failure

* fix(github_copilot): keep per-user session api_base reporting as on base and name Copilot in the non-admin 403

Only an App deployment reports its App host as api_base before a configured api_base.
Per-user OAuth sessions report the same api_base they did on base.
The 403 for a non-admin attaching App credentials now names GitHub Copilot authentication.
The token-dir fixture in the App api_base test is applied with usefixtures.

* fix(github_copilot): report the configured api_base instead of raising when GitHub App settings are incomplete

* test(github_copilot): type the incomplete App settings test parameter

---------

Co-authored-by: Gilad Katz <29776916+giladk1221@users.noreply.github.com>
Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-14 10:33:20 -05:00

924 lines
36 KiB
Python

"""
Router cooldown handlers
- _set_cooldown_deployments: puts a deployment in the cooldown list
- get_cooldown_deployments: returns the list of deployments in the cooldown list
- async_get_cooldown_deployments: ASYNC: returns the list of deployments in the cooldown list
"""
import asyncio
import math
from collections.abc import Collection, Mapping, Sequence
from datetime import datetime
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final
from pydantic import TypeAdapter, ValidationError
import litellm
from litellm._logging import verbose_router_logger
from litellm.constants import (
DEFAULT_COOLDOWN_TIME_SECONDS,
DEFAULT_FAILURE_THRESHOLD_MINIMUM_REQUESTS,
DEFAULT_FAILURE_THRESHOLD_PERCENT,
INTERNAL_CALL_ORIGIN_METADATA_KEY,
SINGLE_DEPLOYMENT_TRAFFIC_FAILURE_THRESHOLD,
)
from litellm.exceptions import MidStreamFallbackError, MissingMessageRoleError
from litellm.litellm_core_utils.credential_accessor import CredentialAccessor
from litellm.litellm_core_utils.litellm_logging import mask_api_base_credentials
from litellm.router_deprecated import renamed_router_param
from litellm.router_utils.cooldown_cache import CooldownCacheValue
from litellm.router_utils.cooldown_callbacks import router_cooldown_event_callback
from litellm.types.llms.anthropic import MESSAGE_THREAD_NOT_FOUND_ERROR_CODE
from litellm.types.router import Deployment
from litellm.types.utils import (
BACKGROUND_RESPONSE_COST_POLL_CALL_ORIGIN,
BACKGROUND_RESPONSE_STATUS_POLL_CALL_ORIGIN,
CooldownDeploymentInfo,
InternalCallOrigin,
)
from litellm.types.videos.utils import VIDEO_ID_CALL_TYPES
from .router_callbacks.track_deployment_metrics import (
get_deployment_failures_for_current_minute,
get_deployment_successes_for_current_minute,
)
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
from litellm.router_api import RoutingContext
Span = _Span
else:
Span = Any
_ADVISOR_ORCHESTRATION_FAILURE_ATTR: Final = "_litellm_advisor_orchestration_failure"
_DEPLOYMENT_SELECTION_FAILURE_ATTR: Final = "_litellm_deployment_selection_failure"
_CREDENTIAL_VALUES_ADAPTER: Final = TypeAdapter(Mapping[str, object])
def mark_advisor_orchestration_failure(exception: BaseException) -> None:
"""Tag an exception as originating from advisor orchestration rather than the
health of the router-selected deployment.
Advisor orchestration failures (an advisor sub-call that targets different
provider/credentials, or the orchestration loop exceeding max_uses) are not
caused by the selected deployment, so they must not be attributed to (and
cool down) that otherwise-healthy deployment. The exception object is tagged
rather than wrapped so its type is preserved and the router's retry/fallback
classification and the client-facing error are unchanged.
"""
setattr(exception, _ADVISOR_ORCHESTRATION_FAILURE_ATTR, True)
def is_advisor_orchestration_failure(exception: BaseException | None) -> bool:
"""Whether ``exception`` was tagged by ``mark_advisor_orchestration_failure``."""
return bool(getattr(exception, _ADVISOR_ORCHESTRATION_FAILURE_ATTR, False))
def mark_deployment_selection_failure(exception: BaseException) -> None:
setattr(exception, _DEPLOYMENT_SELECTION_FAILURE_ATTR, True)
def is_failure_outside_selected_deployment(exception: BaseException | None) -> bool:
return (
is_advisor_orchestration_failure(exception)
or isinstance(exception, MissingMessageRoleError)
or bool(getattr(exception, _DEPLOYMENT_SELECTION_FAILURE_ATTR, False))
)
_BACKGROUND_RESPONSE_POLL_CALL_ORIGINS: Final[frozenset[InternalCallOrigin]] = frozenset(
{BACKGROUND_RESPONSE_COST_POLL_CALL_ORIGIN, BACKGROUND_RESPONSE_STATUS_POLL_CALL_ORIGIN}
)
def is_background_response_poll_not_found(exception: Exception, litellm_params: Mapping[str, object]) -> bool:
"""Whether a background response poll, a status check or the billed read, failed with a provider 404."""
return getattr(exception, "status_code", None) == 404 and any(
isinstance(candidate, Mapping)
and candidate.get(INTERNAL_CALL_ORIGIN_METADATA_KEY) in _BACKGROUND_RESPONSE_POLL_CALL_ORIGINS
for candidate in (litellm_params.get("metadata"), litellm_params.get("litellm_metadata"))
)
def is_video_lookup_not_found(exception: object, failure_kwargs: Mapping[str, object]) -> bool:
"""Whether a call on an existing video id failed with a provider 404: the video is not on that account."""
return getattr(exception, "status_code", None) == 404 and failure_kwargs.get("call_type") in VIDEO_ID_CALL_TYPES
def is_message_thread_not_found(exception: object) -> bool:
"""Whether a message-thread continue failed with Anthropic's 404 ``thread_not_found``: the caller's
``previous_message_id`` is stale and the SDK replays the conversation, the deployment is healthy."""
return getattr(exception, "status_code", None) == 404 and MESSAGE_THREAD_NOT_FOUND_ERROR_CODE in str(exception)
# The calls on an existing response id. ``compact_responses`` is left out: it sends a model and input,
# so its 404 can mean a missing model rather than a missing response.
RESPONSE_ID_CALL_TYPES: Final = frozenset(
{
"aget_responses",
"get_responses",
"adelete_responses",
"delete_responses",
"acancel_responses",
"cancel_responses",
"alist_input_items",
}
)
def is_response_lookup_not_found(exception: object, failure_kwargs: Mapping[str, object]) -> bool:
"""Whether a call on an existing response id failed with a provider 404: the response is not on that account."""
return getattr(exception, "status_code", None) == 404 and failure_kwargs.get("call_type") in RESPONSE_ID_CALL_TYPES
_EXCEPTION_POLICY_FIELDS: Final[tuple[tuple[type, str], ...]] = (
# ContentPolicyViolationError subclasses BadRequestError, so it must be checked first.
(litellm.ContentPolicyViolationError, "ContentPolicyViolationErrorAllowedFails"),
(litellm.BadRequestError, "BadRequestErrorAllowedFails"),
(litellm.AuthenticationError, "AuthenticationErrorAllowedFails"),
(litellm.Timeout, "TimeoutErrorAllowedFails"),
(litellm.RateLimitError, "RateLimitErrorAllowedFails"),
(litellm.InternalServerError, "InternalServerErrorAllowedFails"),
(litellm.ServiceUnavailableError, "ServiceUnavailableErrorAllowedFails"),
(litellm.BadGatewayError, "BadGatewayErrorAllowedFails"),
(litellm.NotFoundError, "NotFoundErrorAllowedFails"),
)
def _first_present(*sources: Mapping[str, object] | None, key: str) -> int | float | None:
"""Return *key* from the first source mapping where it's set, so callers can
support a setting living in more than one deployment config location. Sources
are checked in order from most to least specific to that setting. Only a number
counts: a bool or a string is skipped, so the router default applies."""
for source in sources:
if source is None:
continue
value = source.get(key)
if isinstance(value, int | float) and not isinstance(value, bool):
return value
return None
def _get_deployment_cooldown_policy(
ctx: "RoutingContext",
deployment: str,
) -> tuple[Mapping[str, int] | None, int | None]:
"""Return (allowed_fails_policy, allowed_fails) from deployment model_info, or (None, None).
`model_info` is the only supported location for these two fields (unlike
`cooldown_time`, they have no pre-existing `litellm_params` precedent): `litellm_params`
gets copied wholesale into the actual provider call kwargs (see e.g.
Router._image_generation's `data = deployment["litellm_params"].copy()`), so a new
field placed there would leak into the outgoing LLM request instead of staying
router-internal.
"""
dep: Final = ctx.registry().deployment_dict(deployment)
if dep is None:
return None, None
mi: Final[Mapping[str, Any]] = dep.get("model_info") or MappingProxyType({})
raw: Final = mi.get("allowed_fails_policy")
policy: Final[Mapping[str, int] | None] = raw if isinstance(raw, dict) else None
allowed: Final[int | None] = mi.get("allowed_fails")
return policy, allowed
def _resolve_allowed_fails_from_policy(
policy: Mapping[str, int] | None,
exception: Exception,
) -> int | None:
"""Match *exception* against *policy* and return the configured allowed-fail count, or None."""
if policy is None:
return None
for exc_type, field in _EXCEPTION_POLICY_FIELDS:
if isinstance(exception, exc_type):
value = policy.get(field)
if value is not None:
return value
return None
def _should_cooldown_based_on_deployment_policy(
ctx: "RoutingContext",
deployment: str,
original_exception: Exception,
dep_policy: Mapping[str, int] | None,
dep_allowed_fails: int | None,
is_single_deployment_model_group: bool,
) -> bool:
"""Resolve deployment-level allowed-fails and delegate to the shared counting logic.
When the deployment's policy doesn't cover *original_exception*'s type and no
deployment-wide `allowed_fails` is set either, defer to router-level behavior
instead of forcing an immediate cooldown.
A generic, deployment-wide `allowed_fails` predates this feature's per-exception-type
policy and is a much less deliberate opt-in, so on a single-deployment model group it
still defers to the "avoid cooldowns on single deployment model groups" safety net
(see `_should_cooldown_deployment`'s BASE CASE) rather than silently disabling it. An
explicit, named-exception-type `allowed_fails_policy` entry is unambiguous enough to
override that safety net, matching `_has_explicit_allowed_fails_policy_for_exception`.
"""
allowed_fails_from_policy: Final = _resolve_allowed_fails_from_policy(dep_policy, original_exception)
if (
allowed_fails_from_policy is None
and is_single_deployment_model_group
and (dep_allowed_fails is not None or ctx.settings().allowed_fails_for(original_exception) is None)
):
return False
allowed_fails_override: Final[int | None] = (
allowed_fails_from_policy if allowed_fails_from_policy is not None else dep_allowed_fails
)
cache_key_suffix: Final[str | None] = (
type(original_exception).__name__
if allowed_fails_from_policy is not None
else ("generic" if dep_allowed_fails is not None else None)
)
dep: Final = ctx.registry().deployment_dict(deployment)
cooldown_time_override: Final = (
_first_present(dep.get("model_info"), dep.get("litellm_params"), key="cooldown_time")
if dep is not None
else None
)
return should_cooldown_based_on_allowed_fails_policy(
ctx=ctx,
deployment=deployment,
original_exception=original_exception,
allowed_fails_override=allowed_fails_override,
cooldown_time_override=cooldown_time_override,
cache_key_suffix=cache_key_suffix,
)
def _has_explicit_allowed_fails_policy_for_exception(
ctx: "RoutingContext",
deployment: str | None,
original_exception: Exception,
) -> bool:
"""True if this deployment has an explicit, deployment-level allowed_fails_policy
entry matching *original_exception*'s type.
`_is_cooldown_required` skips cooldown evaluation for most 4XX errors (BadRequestError,
ContentPolicyViolationError) by default, since a generic client error is usually not the
deployment's fault. A deployment-level allowed_fails_policy entry naming that exact
exception type is this PR's own per-deployment opt-in, so it overrides that default.
Deliberately scoped to the deployment level only, and to the named-exception-type
policy dict rather than a plain `allowed_fails` integer: a pre-existing router-wide
`allowed_fails_policy` (or a deployment's generic `allowed_fails`) predates this
feature and must keep its existing behavior for 4XX types `_is_cooldown_required`
already excludes, rather than silently start cooling down deployments whose configs
never opted into this specific override.
"""
if deployment is None:
return False
dep_policy, _ = _get_deployment_cooldown_policy(ctx, deployment)
return _resolve_allowed_fails_from_policy(dep_policy, original_exception) is not None
def _is_cooldown_required(
ctx: "RoutingContext",
model_id: str,
exception_status: str | int,
exception_str: str | None = None,
) -> bool:
"""
A function to determine if a cooldown is required based on the exception status.
Parameters:
model_id (str) The id of the model in the model list
exception_status (Union[str, int]): The status of the exception.
Returns:
bool: True if a cooldown is required, False otherwise.
"""
try:
ignored_strings: Final = ["APIConnectionError"]
if exception_str is not None: # don't cooldown on litellm api connection errors errors
for ignored_string in ignored_strings:
if ignored_string in exception_str:
return False
if isinstance(exception_status, str):
if len(exception_status) == 0:
return False
exception_status = int(exception_status)
if exception_status >= 400 and exception_status < 500:
if exception_status == 429:
# Cool down 429 Rate Limit Errors
return True
elif exception_status in (401, 402, 408, 404):
return True
else:
# Do NOT cool down all other 4XX Errors
return False
else:
# should cool down for all other errors
return True
except Exception:
# Catch all - if any exceptions default to cooling down
return True
def _is_per_user_provider_request(request_kwargs: Mapping[str, object]) -> bool:
from litellm.llms.github_copilot.per_user_auth import (
is_github_copilot_per_user_request,
)
return is_github_copilot_per_user_request(request_kwargs) or is_github_copilot_per_user_request(
request_kwargs.get("litellm_params")
)
def _should_run_cooldown_logic(
ctx: "RoutingContext",
deployment: str | None,
exception_status: str | int,
original_exception: Exception,
time_to_cooldown: float | None = None,
request_kwargs: Mapping[str, object] | None = None,
) -> bool:
"""
Helper that decides if cooldown logic should be run
Returns False if cooldown logic should not be run
Does not run cooldown logic when:
- router.disable_cooldowns is True
- deployment is None
- _is_cooldown_required() returns False
- deployment is in ctx.settings().provider_default_deployment_ids
- exception_status is not one that should be immediately retried (e.g. 401)
"""
if deployment is None or ctx.registry().resolve(deployment, kind="group_of_id") is None:
verbose_router_logger.debug(
"Should Not Run Cooldown Logic: deployment id is none or model group can't be found."
)
return False
if isinstance(
original_exception,
(
litellm.CallerCredentialAuthenticationError,
litellm.CallerCredentialRateLimitError,
),
):
verbose_router_logger.debug(
"Should Not Run Cooldown Logic: caller-credential errors are scoped to one user's connection"
)
return False
if isinstance(original_exception, (litellm.MalformedRequestFieldError, litellm.UnsupportedEndpointError)):
verbose_router_logger.debug(
"Should Not Run Cooldown Logic: litellm rejected the request before calling the deployment"
)
return False
if request_kwargs is not None and _is_per_user_provider_request(request_kwargs):
verbose_router_logger.debug(
"Should Not Run Cooldown Logic: the failure came from one caller's per-user provider session"
)
return False
if deployment is not None:
failed_deployment: Final = ctx.registry().deployment(deployment)
if failed_deployment is not None:
from litellm.llms.github_copilot.per_user_auth import (
github_copilot_per_user_credential_name,
)
failed_litellm_params: Final = getattr(failed_deployment, "litellm_params", None)
if github_copilot_per_user_credential_name(failed_litellm_params) is not None:
verbose_router_logger.debug(
"Should Not Run Cooldown Logic: the failed deployment authenticates per caller"
)
return False
#########################################################
# If time_to_cooldown is 0 or 0.0000000, don't run cooldown logic
#########################################################
if time_to_cooldown is not None and math.isclose(a=time_to_cooldown, b=0.0, abs_tol=1e-9):
verbose_router_logger.debug("Should Not Run Cooldown Logic: time_to_cooldown is effectively 0")
return False
if ctx.settings().disable_cooldowns:
verbose_router_logger.debug("Should Not Run Cooldown Logic: disable_cooldowns is True")
return False
if deployment is None:
verbose_router_logger.debug("Should Not Run Cooldown Logic: deployment is None")
return False
if not _is_cooldown_required(
ctx=ctx,
model_id=deployment,
exception_status=exception_status,
exception_str=str(original_exception),
) and not _has_explicit_allowed_fails_policy_for_exception(
ctx=ctx,
deployment=deployment,
original_exception=original_exception,
):
verbose_router_logger.debug("Should Not Run Cooldown Logic: _is_cooldown_required returned False")
return False
if deployment in ctx.settings().provider_default_deployment_ids:
verbose_router_logger.debug("Should Not Run Cooldown Logic: deployment is in provider_default_deployment_ids")
return False
return True
_FALLBACK_ENTRIES_ADAPTER: Final = TypeAdapter(tuple[object, ...])
_FALLBACK_ENTRY_ADAPTER: Final = TypeAdapter(Mapping[str, list[str | Mapping[str, object]] | str])
def _fallback_target_name(target: str | Mapping[str, object]) -> str:
return target if isinstance(target, str) else str(target.get("model", ""))
def _fallback_target_names(
targets: Sequence[str | Mapping[str, object]] | str,
) -> list[str]: # mutable-ok: mirrors get_fallback_model_group's fallbacks shape
return [targets] if isinstance(targets, str) else [_fallback_target_name(target) for target in targets]
def _fallback_chain_names(
entry: object,
) -> Mapping[str, list[str]] | None: # mutable-ok: mirrors get_fallback_model_group's fallbacks shape
try:
validated: Final = _FALLBACK_ENTRY_ADAPTER.validate_python(entry)
except ValidationError:
return None
return {key: _fallback_target_names(targets) for key, targets in validated.items()}
def _fallback_entries(configured: object) -> tuple[object, ...]:
try:
return _FALLBACK_ENTRIES_ADAPTER.validate_python(configured)
except ValidationError:
return ()
def _has_fallback_group(ctx: "RoutingContext", requested_model_group: str | None) -> bool:
from litellm.router_utils.fallback_event_handlers import get_fallback_model_group
configured: Final[object] = ctx.settings().fallbacks
if requested_model_group is None or not configured:
return False
chains: Final = tuple(
chain for chain in map(_fallback_chain_names, _fallback_entries(configured)) if chain is not None
)
fallback_group, _ = get_fallback_model_group(fallbacks=chains, model_group=requested_model_group)
return bool(fallback_group)
def _should_cooldown_deployment(
ctx: "RoutingContext",
deployment: str,
exception_status: str | int,
original_exception: Exception,
requested_model_group: str | None = None,
) -> bool:
"""
Helper that decides if a deployment should be put in cooldown
Returns True if the deployment should be put in cooldown
Returns False if the deployment should not be put in cooldown
Deployment is put in cooldown when:
- v2 logic (Current):
cooldown if:
- got a 429 error from LLM API
- if %fails/%(successes + fails) > ALLOWED_FAILURE_RATE_PER_MINUTE
- got 401 Auth error, 404 NotFounder - checked by litellm._should_retry()
- v1 logic (Legacy): if allowed fails or allowed fail policy set, coolsdown if num fails in this minute > allowed fails
"""
model_group: Final = ctx.registry().resolve(deployment, kind="group_of_id")
is_single_deployment_model_group = False
if model_group is not None and len(model_group) == 1:
is_single_deployment_model_group = not (
ctx.registry().resolve(requested_model_group, kind="routing_group_alternatives")
or ctx.registry().resolve(deployment, kind="team_model_alternatives")
)
is_lone_deployment: Final = is_single_deployment_model_group and not _has_fallback_group(ctx, requested_model_group)
exception_status_int: Final = cast_exception_status_to_int(exception_status)
dep_policy, dep_allowed_fails = _get_deployment_cooldown_policy(ctx, deployment)
if (
is_single_deployment_model_group
and exception_status_int == 402
and _resolve_allowed_fails_from_policy(dep_policy, original_exception) is None
and ctx.settings().allowed_fails_for(original_exception) is None
):
return False
## CHECK DEPLOYMENT-LEVEL POLICY FIRST (overrides router-level)
if dep_policy is not None or dep_allowed_fails is not None:
return _should_cooldown_based_on_deployment_policy(
ctx,
deployment,
original_exception,
dep_policy,
dep_allowed_fails,
is_lone_deployment,
)
## BASE CASE - single deployment
if ctx.settings().allowed_fails_policy is None and _is_allowed_fails_set_on_router(ctx=ctx) is False:
num_successes_this_minute: Final = get_deployment_successes_for_current_minute(
ctx=ctx, deployment_id=deployment
)
num_fails_this_minute: Final = get_deployment_failures_for_current_minute(ctx=ctx, deployment_id=deployment)
total_requests_this_minute: Final = num_successes_this_minute + num_fails_this_minute
percent_fails = 0.0
if total_requests_this_minute > 0:
percent_fails = num_fails_this_minute / (num_successes_this_minute + num_fails_this_minute)
verbose_router_logger.debug(
"percent fails for deployment = %s, percent fails = %s, num successes = %s, num fails = %s",
deployment,
percent_fails,
num_successes_this_minute,
num_fails_this_minute,
)
if exception_status_int == 429 and not is_single_deployment_model_group:
return True
elif percent_fails == 1.0 and total_requests_this_minute >= SINGLE_DEPLOYMENT_TRAFFIC_FAILURE_THRESHOLD:
# Cooldown if all requests failed and we have reasonable traffic
return True
elif (
percent_fails > DEFAULT_FAILURE_THRESHOLD_PERCENT
and total_requests_this_minute >= DEFAULT_FAILURE_THRESHOLD_MINIMUM_REQUESTS
and not is_single_deployment_model_group # by default we should avoid cooldowns on single deployment model groups
):
# Only apply error rate cooldown when we have enough requests to make the percentage meaningful
return True
elif litellm.should_retry(status_code=exception_status_int) is False:
return True
return False
else:
if is_lone_deployment and ctx.settings().allowed_fails_for(original_exception) is None:
return False
return should_cooldown_based_on_allowed_fails_policy(
ctx=ctx,
deployment=deployment,
original_exception=original_exception,
)
return False
@renamed_router_param("litellm_router_instance")
def set_cooldown_deployments(
ctx: "RoutingContext",
original_exception: Exception,
exception_status: str | int,
deployment: str | None = None,
time_to_cooldown: float | None = None,
requested_model_group: str | None = None,
request_kwargs: Mapping[str, object] | None = None,
) -> bool:
"""
Add a model to the list of models being cooled down for that minute, if it exceeds the allowed fails / minute
or
the exception is not one that should be immediately retried (e.g. 401)
Returns:
- True if the deployment should be put in cooldown
- False if the deployment should not be put in cooldown
"""
verbose_router_logger.debug("checks 'should_run_cooldown_logic'")
if (
_should_run_cooldown_logic(
ctx=ctx,
deployment=deployment,
exception_status=exception_status,
original_exception=original_exception,
time_to_cooldown=time_to_cooldown,
request_kwargs=request_kwargs,
)
is False
or deployment is None
):
verbose_router_logger.debug("should_run_cooldown_logic returned False")
return False
exception_status_int: Final = cast_exception_status_to_int(exception_status)
verbose_router_logger.debug("Attempting to add %s to cooldown list", deployment)
if _should_cooldown_deployment(
ctx=ctx,
deployment=deployment,
exception_status=exception_status,
original_exception=original_exception,
requested_model_group=requested_model_group,
):
ctx.health().cooldowns.add_deployment_to_cooldown(
model_id=deployment,
original_exception=original_exception,
exception_status=exception_status_int,
cooldown_time=time_to_cooldown,
)
# Trigger cooldown callback handler
asyncio.create_task(
router_cooldown_event_callback(
ctx=ctx,
deployment_id=deployment,
exception_status=exception_status,
cooldown_time=time_to_cooldown,
)
)
return True
return False
_set_cooldown_deployments = set_cooldown_deployments
@renamed_router_param("litellm_router_instance")
async def async_get_cooldown_deployments(
ctx: "RoutingContext",
parent_otel_span: Span | None,
) -> list[str]:
"""
Async implementation of 'get_cooldown_deployments'
"""
model_ids: Final = ctx.registry().names(kind="ids")
cooldown_models: Final = await ctx.health().cooldowns.async_get_active_cooldowns(
model_ids=model_ids,
parent_otel_span=parent_otel_span,
)
cached_value_deployment_ids = []
if (
cooldown_models is not None
and isinstance(cooldown_models, list)
and len(cooldown_models) > 0
and isinstance(cooldown_models[0], tuple)
):
cached_value_deployment_ids = [cv[0] for cv in cooldown_models]
verbose_router_logger.debug("retrieve cooldown models: %s", cooldown_models)
return cached_value_deployment_ids
_async_get_cooldown_deployments = async_get_cooldown_deployments
@renamed_router_param("litellm_router_instance")
async def async_get_cooldown_deployments_with_debug_info(
ctx: "RoutingContext",
parent_otel_span: Span | None,
) -> list[tuple[str, CooldownCacheValue]]:
"""
Async implementation of 'get_cooldown_deployments'
"""
model_ids: Final = ctx.registry().names(kind="ids")
cooldown_models: Final = await ctx.health().cooldowns.async_get_active_cooldowns(
model_ids=model_ids, parent_otel_span=parent_otel_span
)
verbose_router_logger.debug("retrieve cooldown models: %s", cooldown_models)
return cooldown_models
_async_get_cooldown_deployments_with_debug_info = async_get_cooldown_deployments_with_debug_info
@renamed_router_param("litellm_router_instance")
def get_cooldown_deployments(ctx: "RoutingContext", parent_otel_span: Span | None) -> list[str]:
"""
Get the list of models being cooled down for this minute
"""
# get the current cooldown list for that minute
# ----------------------
# Return cooldown models
# ----------------------
model_ids: Final = ctx.registry().names(kind="ids")
cooldown_models: Final = ctx.health().cooldowns.get_active_cooldowns(
model_ids=model_ids, parent_otel_span=parent_otel_span
)
cached_value_deployment_ids = []
if (
cooldown_models is not None
and isinstance(cooldown_models, list)
and len(cooldown_models) > 0
and isinstance(cooldown_models[0], tuple)
):
cached_value_deployment_ids = [cv[0] for cv in cooldown_models]
return cached_value_deployment_ids
_get_cooldown_deployments = get_cooldown_deployments
def _deployment_api_base(ctx: "RoutingContext", model_id: str) -> str | None:
deployment: Final = ctx.registry().deployment(model_id)
api_base: Final = deployment.litellm_params.api_base if deployment else None
return None if api_base is None else mask_api_base_credentials(api_base)
@renamed_router_param("litellm_router_instance")
def get_cooldown_deployment_info(
ctx: "RoutingContext", route_model_ids: Collection[str], cooldown_list: Sequence[str]
) -> tuple[CooldownDeploymentInfo, ...]:
"""
The deployments the router resolved for this request (`route_model_ids`) that are in `cooldown_list`, each
with its masked api_base
"""
return tuple(
CooldownDeploymentInfo(model_id=model_id, api_base=_deployment_api_base(ctx, model_id))
for model_id in cooldown_list
if model_id in route_model_ids
)
@renamed_router_param("litellm_router_instance")
def should_cooldown_based_on_allowed_fails_policy(
ctx: "RoutingContext",
deployment: str,
original_exception: Exception,
allowed_fails_override: int | None = None,
cooldown_time_override: float | None = None,
cache_key_suffix: str | None = None,
) -> bool:
"""
Check if fails are within the allowed limit and update the number of fails.
When *allowed_fails_override* / *cooldown_time_override* are supplied they
take precedence over the router-level values (used by deployment-level overrides).
The counter lives in the cooldown store (Redis when configured), so
every worker process increments the same key and the threshold applies fleet-wide.
When *cache_key_suffix* is supplied the fail counter is keyed as
``deployment:{deployment}:allowed_fails:{cache_key_suffix}`` so that different
exception types are tracked independently per deployment.
Returns:
- True if fails exceed the allowed limit (should cooldown)
- False if fails are within the allowed limit (should not cooldown)
"""
allowed_fails_from_policy: Final = ctx.settings().allowed_fails_for(original_exception)
allowed_fails: Final = (
allowed_fails_override
if allowed_fails_override is not None
else (allowed_fails_from_policy if allowed_fails_from_policy is not None else ctx.settings().allowed_fails)
)
cooldown_time: Final = (
cooldown_time_override
if cooldown_time_override is not None
else (ctx.settings().cooldown_time or DEFAULT_COOLDOWN_TIME_SECONDS)
)
updated_fails: Final = ctx.health().cooldowns.cooldown_store.increment_allowed_fails(
deployment, cache_key_suffix, cooldown_time
)
return updated_fails > allowed_fails
def _is_allowed_fails_set_on_router(
ctx: "RoutingContext",
) -> bool:
"""
Check if Router.allowed_fails was passed to the Router or is a Non-default Value
Returns:
- True if allowed_fails was passed to the Router, even when it equals the default
- True if Router.allowed_fails is a Non-default Value
- False if Router.allowed_fails is None, or is the Default Value and was not passed
"""
if ctx.settings().allowed_fails is None:
return False
if ctx.explicit_allowed_fails is not None:
return True
if ctx.settings().allowed_fails != litellm.allowed_fails:
return True
return False
def cast_exception_status_to_int(exception_status: object) -> int:
if isinstance(exception_status, str):
try:
exception_status = int(exception_status)
except Exception:
verbose_router_logger.debug(
"Unable to cast exception status to int %s. Defaulting to status=500.", exception_status
)
exception_status = 500
# A bool or a number no HTTP status can be is read as a 500, as the Rust router core reads it.
if (
isinstance(exception_status, bool)
or not isinstance(exception_status, int)
or not 0 <= exception_status <= 65535
):
return 500
return exception_status
def is_caller_timeout_408(
model_call_details: Mapping[str, object], exception_status: str | int, ended: datetime | None = None
) -> bool:
"""A 408 that arrives before the caller-set timeout could have fired came from the provider.
``ended`` overrides ``model_call_details["end_time"]`` for callers that run before the
failure logger has stamped the current API call's end time."""
if cast_exception_status_to_int(exception_status) != 408:
return False
litellm_params: Final = model_call_details.get("litellm_params")
if not isinstance(litellm_params, Mapping) or not litellm_params.get("client_side_timeout"):
return False
timeout: Final = litellm_params.get("timeout")
started: Final = model_call_details.get("api_call_start_time") or model_call_details.get("start_time")
finished: Final = ended if ended is not None else model_call_details.get("end_time")
if not isinstance(timeout, (int, float)) or not isinstance(started, datetime) or not isinstance(finished, datetime):
return False
return (finished - started).total_seconds() >= timeout
def is_stream_stall(exception: BaseException) -> bool:
return isinstance(exception, litellm.Timeout) and isinstance(exception.__cause__, MidStreamFallbackError)
def is_caller_entra_credential_failure(
deployment: Deployment | None,
router_defaults: Mapping[str, object],
model_call_details: Mapping[str, object],
exception_status: str | int,
exception: BaseException,
) -> bool:
if cast_exception_status_to_int(exception_status) != 401 or deployment is None:
return False
from litellm.llms.azure.common_utils import caused_by_entra_rejection
if not caused_by_entra_rejection(exception):
return False
from litellm.llms.azure_ai.common_utils import AZURE_ENTRA_LITELLM_PARAM_KEYS, azure_entra_environment_defaults
call_params: Final = _CREDENTIAL_VALUES_ADAPTER.validate_python(model_call_details.get("litellm_params") or {})
credential_name: Final = deployment.litellm_params.litellm_credential_name
configured_by_precedence: Final[tuple[Mapping[str, object], ...]] = (
router_defaults,
_CREDENTIAL_VALUES_ADAPTER.validate_python(deployment.litellm_params.model_dump(exclude_none=True)),
_CREDENTIAL_VALUES_ADAPTER.validate_python(
CredentialAccessor.get_credential_values(credential_name) if credential_name is not None else {}
),
)
environment: Final = azure_entra_environment_defaults()
return any(
call_params.get(key) is not None
and (call_params.get(key) or environment.get(key))
!= (_first_configured(configured_by_precedence, key) or environment.get(key))
for key in AZURE_ENTRA_LITELLM_PARAM_KEYS
)
def _first_configured(sources: tuple[Mapping[str, object], ...], key: str) -> object:
return next((value for source in sources if (value := source.get(key)) is not None), None)
def is_caller_scoped_auth_failure(deployment: Deployment | None, exception_status: str | int) -> bool:
if cast_exception_status_to_int(exception_status) not in (401, 403) or deployment is None:
return False
token_exchange_endpoint: Final = deployment.litellm_params.token_exchange_endpoint
if isinstance(token_exchange_endpoint, str) and token_exchange_endpoint:
return True
credential_name: Final = deployment.litellm_params.litellm_credential_name
if credential_name is None:
return False
credential_values: Final[Mapping[str, object]] = _CREDENTIAL_VALUES_ADAPTER.validate_python(
CredentialAccessor.get_credential_values(credential_name)
)
credential_token_exchange_endpoint: Final = credential_values.get("token_exchange_endpoint")
return isinstance(credential_token_exchange_endpoint, str) and bool(credential_token_exchange_endpoint)