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
refactor(proxy): tighten model deprecation typing and cover the endpoint
mateo8f1aea5e0a6f
diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.pyindex 12b5d7525dc..b40f4ac03e0 100644--- a/litellm/integrations/SlackAlerting/slack_alerting.py+++ b/litellm/integrations/SlackAlerting/slack_alerting.py@@ -40,6 +40,9 @@ from litellm.proxy._types import (from litellm.repositories.team_repository import TeamRepositoryfrom litellm.repositories.user_repository import UserRepositoryfrom litellm.types.integrations.slack_alerting import *+from litellm.types.proxy.model_deprecation import (+ DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS,+)from ..email_templates.templates import *from .batching_handler import send_to_webhook, squash_payloads@@ -1038,20 +1041,9 @@ Model Info:async def model_removed_alert(self, model_name: str):pass- async def send_model_deprecation_alert(- self, llm_router: Optional[Any] = None- ) -> bool:- """Aggregate deprecation metadata for the configured models and alert.-- Returns ``True`` when an alert payload was dispatched, ``False``- otherwise. The ``send_alert`` helper itself is responsible for honoring- the user's webhook configuration; this method only owns producing the- message and choosing whether to send it.- """- if (- self.alerting is None- or AlertType.model_deprecation_warnings not in self.alert_types- ):+ async def send_model_deprecation_alert(self, llm_router: Router | None = None) -> bool:+ """Alert on the router's deprecated and imminent models, True when one was sent"""+ if self.alerting is None or AlertType.model_deprecation_warnings not in self.alert_types:return Falsefrom litellm.proxy.common_utils.model_deprecation import (@@ -1059,27 +1051,18 @@ Model Info:format_deprecation_alert_message,)- try:- snapshot = collect_model_deprecations(llm_router=llm_router)- except Exception as e:- verbose_proxy_logger.exception(- "Error collecting model deprecation snapshot: %s", e- )- return False-- message = format_deprecation_alert_message(snapshot)+ snapshot: Final = collect_model_deprecations(llm_router=llm_router)+ message: Final = format_deprecation_alert_message(snapshot)if message is None:return False- level: Literal["Low", "Medium", "High"] = (- "High" if snapshot.deprecated else "Medium"- )+ level: Final[Literal["Low", "Medium", "High"]] = "High" if snapshot.deprecated else "Medium"await self.send_alert(message=message,level=level,alert_type=AlertType.model_deprecation_warnings,- alerting_metadata={+ alerting_metadata={ # mutable-ok: send_alert takes a dict payload"deprecated_count": len(snapshot.deprecated),"imminent_count": len(snapshot.imminent),"upcoming_count": len(snapshot.upcoming),@@ -1087,30 +1070,16 @@ Model Info:)return True- async def _run_scheduled_deprecation_check(self, llm_router: Optional[Any] = None):- """Periodic background task that emits a model deprecation alert.-- Runs immediately on startup (so operators see the current state in- Slack) and then sleeps ``DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS``- between runs. Exits silently if the alert type is not enabled.- """- from litellm.types.proxy.model_deprecation import (- DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS,- )-- if (- self.alerting is None- or AlertType.model_deprecation_warnings not in self.alert_types- ):+ async def _run_scheduled_deprecation_check(self, llm_router: Router | None = None) -> None:+ """Alert once on startup, then daily, so operators see the current state"""+ if self.alerting is None or AlertType.model_deprecation_warnings not in self.alert_types:returnwhile True:try:await self.send_model_deprecation_alert(llm_router=llm_router)- except Exception as e:- verbose_proxy_logger.exception(- "Error in model deprecation alert loop: %s", e- )+ except Exception as e: # noqa: BLE001 # a failed alert must not kill the daily loop+ verbose_proxy_logger.exception("Error in model deprecation alert loop: %s", e)await asyncio.sleep(DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS)async def send_webhook_alert(self, webhook_event: WebhookEvent) -> bool:diff --git a/litellm/proxy/common_utils/model_deprecation.py b/litellm/proxy/common_utils/model_deprecation.pyindex 7a614c7cfa8..4a5654eed1f 100644--- a/litellm/proxy/common_utils/model_deprecation.py+++ b/litellm/proxy/common_utils/model_deprecation.py@@ -1,51 +1,35 @@-"""Helpers for surfacing model deprecation/sunset information.--This module reads ``deprecation_date`` metadata that is bundled in-``model_prices_and_context_window.json`` (exposed at runtime via-``litellm.model_cost``) and classifies the proxy's configured models into-``upcoming``, ``imminent`` and ``deprecated`` buckets. It is the single-source of truth used by both the ``/model/deprecations`` endpoint and the-proactive Slack alert.--Resolution order for a deployment's deprecation date:--1. ``model_info.deprecation_date`` – an explicit override on the deployment.-2. ``model_info.base_model`` looked up in ``litellm.model_cost``.-3. The ``litellm_params.model`` string looked up in ``litellm.model_cost``.--Models without any deprecation metadata are skipped silently (most models-are not deprecated, and we don't want to pollute the response).-"""-from __future__ import annotations+from collections.abc import Mapping, Sequence+from dataclasses import dataclassfrom datetime import date, datetime, timezone-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple+from itertools import groupby+from types import MappingProxyType+from typing import TYPE_CHECKING, Finalimport litellmfrom litellm._logging import verbose_loggerfrom litellm.types.proxy.model_deprecation import (DEFAULT_DEPRECATION_WARN_DAYS,+ DeprecationStatus,ModelDeprecationInfo,ModelDeprecationResponse,)if TYPE_CHECKING:- from litellm.router import Router as _Router+ from litellm.router import Router- Router = _Router-else:- Router = Any+_NO_MODEL_METADATA: Final[Mapping[str, object]] = MappingProxyType({})-def _parse_deprecation_date(raw_value: Any) -> Optional[date]:- """Parse a ``deprecation_date`` string in YYYY-MM-DD form.+@dataclass(frozen=True, slots=True)+class _ResolvedDeprecation:+ deprecation_date: date+ litellm_model: str | None+ litellm_provider: str | None- Returns ``None`` for missing, malformed, or sentinel placeholder values- (the JSON map ships a documentation sentinel of the form ``"date when..."``).- """- if raw_value is None:- return None++def _parse_deprecation_date(raw_value: object) -> date | None:if isinstance(raw_value, datetime):return raw_value.date()if isinstance(raw_value, date):@@ -53,68 +37,65 @@ def _parse_deprecation_date(raw_value: Any) -> Optional[date]:if not isinstance(raw_value, str):return Nonetry:- return datetime.strptime(raw_value.strip(), "%Y-%m-%d").date()+ return date.fromisoformat(raw_value.strip())except ValueError:return None-def _lookup_deprecation_date_from_cost_map(- model_key: Optional[str],-) -> Tuple[Optional[date], Optional[str]]:- """Look up a deprecation date in ``litellm.model_cost`` for ``model_key``.-- Returns a tuple of (deprecation_date, litellm_provider).- """- if not model_key:- return None, None- entry = litellm.model_cost.get(model_key)- if not isinstance(entry, dict):- return None, None- return (- _parse_deprecation_date(entry.get("deprecation_date")),- entry.get("litellm_provider"),+def _cost_map_lookup(model_key: object) -> _ResolvedDeprecation | None:+ if not isinstance(model_key, str) or not model_key:+ return None+ entry: Final = litellm.model_cost.get(model_key)+ if not isinstance(entry, Mapping):+ return None+ parsed: Final = _parse_deprecation_date(entry.get("deprecation_date"))+ if parsed is None:+ return None+ provider: Final = entry.get("litellm_provider")+ return _ResolvedDeprecation(+ deprecation_date=parsed,+ litellm_model=model_key,+ litellm_provider=provider if isinstance(provider, str) else None,)-def _resolve_deployment_deprecation(- deployment: Dict[str, Any],-) -> Tuple[Optional[date], Optional[str], Optional[str]]:- """Resolve a deployment's deprecation metadata.-- Returns a tuple of (deprecation_date, litellm_model, litellm_provider).- """- model_info = deployment.get("model_info") or {}- explicit = _parse_deprecation_date(model_info.get("deprecation_date"))- if explicit is not None:- litellm_params = deployment.get("litellm_params") or {}- return (- explicit,- litellm_params.get("model"),- model_info.get("litellm_provider"),- )+def _mapping_field(deployment: Mapping[str, object], key: str) -> Mapping[str, object]:+ value: Final = deployment.get(key)+ return value if isinstance(value, Mapping) else _NO_MODEL_METADATA- base_model = model_info.get("base_model")- dep_date, provider = _lookup_deprecation_date_from_cost_map(base_model)- if dep_date is not None:- return dep_date, base_model, provider- litellm_params = deployment.get("litellm_params") or {}- raw_model = litellm_params.get("model")- dep_date, provider = _lookup_deprecation_date_from_cost_map(raw_model)- if dep_date is not None:- return dep_date, raw_model, provider-- if isinstance(raw_model, str) and "/" in raw_model:- # Try the un-prefixed lookup (e.g. "openai/gpt-4o" → "gpt-4o").- bare = raw_model.split("/", 1)[1]- dep_date, provider = _lookup_deprecation_date_from_cost_map(bare)- if dep_date is not None:- return dep_date, bare, provider+def _resolve_deployment_deprecation(+ deployment: Mapping[str, object],+) -> _ResolvedDeprecation | None:+ """Resolve a deployment's deprecation date, preferring its explicit override"""+ model_info: Final = _mapping_field(deployment, "model_info")+ raw_model: Final = _mapping_field(deployment, "litellm_params").get("model")++ override: Final = _parse_deprecation_date(model_info.get("deprecation_date"))+ if override is not None:+ provider: Final = model_info.get("litellm_provider")+ return _ResolvedDeprecation(+ deprecation_date=override,+ litellm_model=raw_model if isinstance(raw_model, str) else None,+ litellm_provider=provider if isinstance(provider, str) else None,+ )- return None, raw_model, model_info.get("litellm_provider")+ unprefixed: Final = raw_model.split("/", 1)[1] if isinstance(raw_model, str) and "/" in raw_model else None+ return next(+ (+ resolved+ for resolved in (+ _cost_map_lookup(model_info.get("base_model")),+ _cost_map_lookup(raw_model),+ _cost_map_lookup(unprefixed),+ )+ if resolved is not None+ ),+ None,+ )-def _classify(days_until: int, warn_within_days: int) -> str:+def _classify(days_until: int, warn_within_days: int) -> DeprecationStatus:if days_until < 0:return "deprecated"if days_until <= warn_within_days:@@ -122,128 +103,119 @@ def _classify(days_until: int, warn_within_days: int) -> str:return "upcoming"-def _model_dump_compat(deployment: Any) -> Dict[str, Any]:- """Return a plain dict for both pydantic models and dicts."""- if isinstance(deployment, dict):- return deployment- if hasattr(deployment, "model_dump"):- return deployment.model_dump(exclude_none=True)- if hasattr(deployment, "dict"):- return deployment.dict()- return dict(deployment)+def _build_info(deployment: Mapping[str, object], today: date, warn_within_days: int) -> ModelDeprecationInfo | None:+ model_name: Final = deployment.get("model_name")+ if not isinstance(model_name, str) or not model_name:+ return None+ resolved: Final = _resolve_deployment_deprecation(deployment)+ if resolved is None:+ return None-def collect_model_deprecations(- llm_router: Optional[Router],- warn_within_days: int = DEFAULT_DEPRECATION_WARN_DAYS,- today: Optional[date] = None,-) -> ModelDeprecationResponse:- """Aggregate deprecation info for all deployments configured on the router.+ days_until: Final = (resolved.deprecation_date - today).days+ return ModelDeprecationInfo(+ model_name=model_name,+ litellm_model=resolved.litellm_model,+ deprecation_date=resolved.deprecation_date,+ days_until_deprecation=days_until,+ status=_classify(days_until, warn_within_days),+ litellm_provider=resolved.litellm_provider,+ )- De-duplicates by ``(model_name, deprecation_date)`` so multi-deployment- model groups (load-balanced across regions) only surface once per- deprecation date.- """- snapshot_time = datetime.now(timezone.utc)- today = today or snapshot_time.date()- response = ModelDeprecationResponse(- warn_within_days=warn_within_days,- checked_at=snapshot_time,+def _dedupe(+ models: Sequence[ModelDeprecationInfo],+) -> tuple[ModelDeprecationInfo, ...]:+ """Report a model group carrying the same date on several deployments once"""+ ordered: Final = sorted(models, key=lambda model: (model.model_name, model.deprecation_date))+ return tuple(+ next(group) for _, group in groupby(ordered, key=lambda model: (model.model_name, model.deprecation_date)))- if llm_router is None:- return response-- seen: set = set()- deployments = llm_router.get_model_list() or []- for deployment in deployments:- deployment_dict = _model_dump_compat(deployment)- model_name = deployment_dict.get("model_name")- if not model_name:- continue- dep_date, litellm_model, provider = _resolve_deployment_deprecation(- deployment_dict- )- if dep_date is None:- continue-- dedup_key = (model_name, dep_date.isoformat())- if dedup_key in seen:- continue- seen.add(dedup_key)-- days_until = (dep_date - today).days- status = _classify(days_until, warn_within_days)-- info = ModelDeprecationInfo(- model_name=model_name,- litellm_model=litellm_model,- deprecation_date=dep_date,- days_until_deprecation=days_until,- status=status,- litellm_provider=provider,+def _bucket(models: Sequence[ModelDeprecationInfo], status: DeprecationStatus) -> tuple[ModelDeprecationInfo, ...]:+ return tuple(+ sorted(+ (model for model in models if model.status == status),+ key=lambda model: model.deprecation_date,)+ )- if status == "deprecated":- response.deprecated.append(info)- elif status == "imminent":- response.imminent.append(info)- else:- response.upcoming.append(info)- response.deprecated.sort(key=lambda m: m.deprecation_date)- response.imminent.sort(key=lambda m: m.deprecation_date)- response.upcoming.sort(key=lambda m: m.deprecation_date)+def collect_model_deprecations(+ llm_router: Router | None,+ warn_within_days: int = DEFAULT_DEPRECATION_WARN_DAYS,+ today: date | None = None,+) -> ModelDeprecationResponse:+ """Bucket every deployment carrying a deprecation date by how urgent it is"""+ snapshot_time: Final = datetime.now(timezone.utc)+ effective_today: Final = today or snapshot_time.date()+ deployments: Final = (llm_router.get_model_list() or ()) if llm_router is not None else ()++ deduped: Final = _dedupe(+ tuple(+ info+ for info in (_build_info(deployment, effective_today, warn_within_days) for deployment in deployments)+ if info is not None+ )+ )verbose_logger.debug(- "model_deprecation: deprecated=%d imminent=%d upcoming=%d",- len(response.deprecated),- len(response.imminent),- len(response.upcoming),+ "model_deprecation: %d/%d deployments carry a deprecation date",+ len(deduped),+ len(deployments),)- return response+ return ModelDeprecationResponse(+ deprecated=_bucket(deduped, "deprecated"),+ imminent=_bucket(deduped, "imminent"),+ upcoming=_bucket(deduped, "upcoming"),+ warn_within_days=warn_within_days,+ checked_at=snapshot_time,+ )+++def _format_entry(info: ModelDeprecationInfo) -> str:+ suffix: Final = (+ f"already deprecated {abs(info.days_until_deprecation)}d ago"+ if info.days_until_deprecation < 0+ else f"in {info.days_until_deprecation}d"+ )+ return (+ f"• `{info.model_name}` "+ f"(provider: {info.litellm_provider or 'unknown'}, "+ f"deprecates {info.deprecation_date.isoformat()}, {suffix})"+ )def format_deprecation_alert_message(snapshot: ModelDeprecationResponse,-) -> Optional[str]:- """Format a Slack-friendly alert message for the warning buckets.+) -> str | None:+ """Render the alert for the deprecated and imminent buckets, None when both are empty- Only ``deprecated`` and ``imminent`` models are included; ``upcoming``- models are intentionally omitted to avoid alert fatigue. Returns- ``None`` when there is nothing to alert on.+ Upcoming models are left out of the alert to keep it actionable."""if not snapshot.deprecated and not snapshot.imminent:return None- lines: List[str] = ["*⚠️ Model Deprecation Warning*"]-- def _format_entry(info: ModelDeprecationInfo) -> str:- suffix = (- f"already deprecated {abs(info.days_until_deprecation)}d ago"- if info.days_until_deprecation < 0- else f"in {info.days_until_deprecation}d"- )- return (- f"• `{info.model_name}` "- f"(provider: {info.litellm_provider or 'unknown'}, "- f"deprecates {info.deprecation_date.isoformat()} – {suffix})"+ deprecated_section: Final = (+ ("\n*Already deprecated:*", *(_format_entry(i) for i in snapshot.deprecated)) if snapshot.deprecated else ()+ )+ imminent_section: Final = (+ (+ f"\n*Deprecating within {snapshot.warn_within_days} days:*",+ *(_format_entry(i) for i in snapshot.imminent),)-- if snapshot.deprecated:- lines.append("\n*Already deprecated:*")- lines.extend(_format_entry(i) for i in snapshot.deprecated)-- if snapshot.imminent:- lines.append(f"\n*Deprecating within {snapshot.warn_within_days} days:*")- lines.extend(_format_entry(i) for i in snapshot.imminent)-- lines.append(- "\nPlan migrations to a supported model. See "- "https://docs.litellm.ai/docs/proxy/model_management for guidance."+ if snapshot.imminent+ else ())- return "\n".join(lines)+ return "\n".join(+ (+ "*⚠️ Model Deprecation Warning*",+ *deprecated_section,+ *imminent_section,+ "\nPlan migrations to a supported model. See "+ "https://docs.litellm.ai/docs/proxy/model_management for guidance.",+ )+ )diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 3d137732075..d4101f56d33 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -625,14 +625,14 @@ from litellm.types.proxy.control_plane_endpoints import WorkerRegistryEntryfrom litellm.types.proxy.management_endpoints.model_management_endpoints import (ModelGroupInfoProxy,)-from litellm.types.proxy.model_deprecation import (- DEFAULT_DEPRECATION_WARN_DAYS,- ModelDeprecationResponse,-)from litellm.types.proxy.management_endpoints.ui_sso import (DefaultTeamSSOParams,LiteLLM_UpperboundKeyGenerateParams,)+from litellm.types.proxy.model_deprecation import (+ DEFAULT_DEPRECATION_WARN_DAYS,+ ModelDeprecationResponse,+)from litellm.types.realtime import RealtimeQueryParamsfrom litellm.types.router import (DeploymentTypedDict,@@ -13443,18 +13443,17 @@ async def model_info_v1(@router.get("/model/deprecations",- tags=["model management"],- dependencies=[Depends(user_api_key_auth)],+ tags=("model management",),+ dependencies=(Depends(user_api_key_auth),),response_model=ModelDeprecationResponse,)@router.get("/v1/model/deprecations",- tags=["model management"],- dependencies=[Depends(user_api_key_auth)],+ tags=("model management",),+ dependencies=(Depends(user_api_key_auth),),response_model=ModelDeprecationResponse,)async def model_deprecations(- user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),warn_within_days: int = DEFAULT_DEPRECATION_WARN_DAYS,) -> ModelDeprecationResponse:"""List models with known deprecation/sunset dates, bucketed by urgency.@@ -13464,13 +13463,13 @@ async def model_deprecations(models configured on this proxy.Parameters:- warn_within_days: Window (in days) used to bucket "imminent" models.- Defaults to `LITELLM_MODEL_DEPRECATION_WARN_DAYS` env var (or 30).+ warn_within_days: Window (in days) used to bucket "imminent" models,+ 30 by default.Returns:A payload with three lists of `ModelDeprecationInfo` entries:- - `deprecated`: deprecation date is in the past — these requests may+ - `deprecated`: deprecation date is in the past, so these requests mayfail at any time.- `imminent`: deprecation date is within `warn_within_days` from today.- `upcoming`: deprecation date is further out.@@ -13481,10 +13480,7 @@ async def model_deprecations(-H 'Authorization: Bearer sk-1234'```"""- global llm_router- return collect_model_deprecations(- llm_router=llm_router, warn_within_days=warn_within_days- )+ return collect_model_deprecations(llm_router=llm_router, warn_within_days=warn_within_days)def _get_model_group_info(diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex f98df15a346..8de4605ecd2 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -484,14 +484,11 @@ class ProxyLogging:if (self.slack_alerting_instance is not None- and AlertType.model_deprecation_warnings- in self.slack_alerting_instance.alert_types+ and AlertType.model_deprecation_warnings in self.slack_alerting_instance.alert_typesand not self.deprecation_check_started):asyncio.create_task(- self.slack_alerting_instance._run_scheduled_deprecation_check(- llm_router=llm_router- )+ self.slack_alerting_instance._run_scheduled_deprecation_check(llm_router=llm_router)) # RUN MODEL DEPRECATION ALERT LOOP (if scheduled)self.deprecation_check_started = Truediff --git a/litellm/types/proxy/model_deprecation.py b/litellm/types/proxy/model_deprecation.pyindex 8cf98f7a1d5..74b7ea866f4 100644--- a/litellm/types/proxy/model_deprecation.py+++ b/litellm/types/proxy/model_deprecation.py@@ -1,89 +1,50 @@-"""Type definitions for model deprecation tracking and proactive alerts.--The proxy reads deprecation/sunset metadata from-``litellm.model_cost`` (sourced from ``model_prices_and_context_window.json``)-and surfaces it through the ``/model/deprecations`` endpoint and Slack-alerting. These types describe the response payload and the alert payload.-"""-from __future__ import annotationsfrom datetime import date, datetime-from typing import List, Optional+from typing import Final, Literalfrom pydantic import BaseModel, Field+DEFAULT_DEPRECATION_WARN_DAYS: Final = 30-DEFAULT_DEPRECATION_WARN_DAYS = 30-"""Default warning window (in days) for the ``imminent`` bucket.--Matches the typical migration window most LLM providers offer between-deprecation announcement and removal. Callers of ``/model/deprecations``-can override this per-request via the ``?warn_within_days=N`` query-parameter without restarting the proxy.-"""--DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS = 24 * 60 * 60-"""How often the periodic background check runs. Once per day."""+DEFAULT_DEPRECATION_CHECK_INTERVAL_SECONDS: Final = 24 * 60 * 60--DeprecationStatusLiteral = str-"""One of ``"upcoming"``, ``"imminent"``, ``"deprecated"``.--* ``upcoming`` – deprecation is scheduled but more than the warn window away.-* ``imminent`` – deprecation date is within ``warn_within_days`` from today.-* ``deprecated`` – deprecation date has already passed.-"""+DeprecationStatus = Literal["upcoming", "imminent", "deprecated"]class ModelDeprecationInfo(BaseModel):- """Per-model deprecation metadata returned by ``/model/deprecations``."""-- model_name: str = Field(- description="The public name of the model on the proxy (model_group)."- )- litellm_model: Optional[str] = Field(+ model_name: str = Field(description="The public name of the model on the proxy (model_group).")+ litellm_model: str | None = Field(default=None,description="The underlying litellm model string the deprecation date is sourced from.",)- deprecation_date: date = Field(- description="The date (UTC) when the model becomes deprecated."- )+ deprecation_date: date = Field(description="The date (UTC) when the model becomes deprecated.")days_until_deprecation: int = Field(+ description=("Days remaining until the deprecation date. Negative if the model is already deprecated."),+ )+ status: DeprecationStatus = Field(description=(- "Days remaining until the deprecation date. Negative if the model "- "is already deprecated."+ "'deprecated' if the date has passed, 'imminent' if it falls within warn_within_days, 'upcoming' otherwise."),)- status: DeprecationStatusLiteral = Field(- description="One of 'upcoming', 'imminent', or 'deprecated'.",- )- litellm_provider: Optional[str] = Field(- default=None, description="The provider this model belongs to."- )+ litellm_provider: str | None = Field(default=None, description="The provider this model belongs to.")class ModelDeprecationResponse(BaseModel):- """Response payload for ``GET /model/deprecations``."""-- deprecated: List[ModelDeprecationInfo] = Field(+ deprecated: list[ModelDeprecationInfo] = Field(default_factory=list,description="Models whose deprecation date has already passed.",)- imminent: List[ModelDeprecationInfo] = Field(+ imminent: list[ModelDeprecationInfo] = Field(default_factory=list,description=(- "Models whose deprecation date is within ``warn_within_days`` from "+ "Models whose deprecation date is within warn_within_days from ""today and require immediate migration planning."),)- upcoming: List[ModelDeprecationInfo] = Field(+ upcoming: list[ModelDeprecationInfo] = Field(default_factory=list,description="Models with a future deprecation date outside the warn window.",)- warn_within_days: int = Field(- description="The window (in days) used to bucket 'imminent' models."- )- checked_at: datetime = Field(- description="UTC timestamp when the deprecation snapshot was generated."- )+ warn_within_days: int = Field(description="The window (in days) used to bucket 'imminent' models.")+ checked_at: datetime = Field(description="UTC timestamp when the deprecation snapshot was generated.")diff --git a/tests/test_litellm/proxy/common_utils/test_model_deprecation.py b/tests/test_litellm/proxy/common_utils/test_model_deprecation.pyindex c873e2494f9..103f9383f5a 100644--- a/tests/test_litellm/proxy/common_utils/test_model_deprecation.py+++ b/tests/test_litellm/proxy/common_utils/test_model_deprecation.py@@ -6,7 +6,7 @@ Slack integration — so they can run without the full proxy stack.import osimport sys-from datetime import date+from datetime import date, datetime, timezonefrom unittest.mock import MagicMock@@ -50,6 +50,11 @@ class TestParseDeprecationDate:def test_should_return_none_for_unsupported_type(self):assert _parse_deprecation_date(12345) is None+ def test_should_narrow_datetime_to_date(self):+ assert _parse_deprecation_date(+ datetime(2026, 12, 31, 23, 59, tzinfo=timezone.utc)+ ) == date(2026, 12, 31)+class TestClassify:def test_should_classify_past_dates_as_deprecated(self):@@ -196,6 +201,56 @@ class TestCollectModelDeprecations:assert len(snapshot.imminent) == 1+ def test_should_resolve_via_unprefixed_model_name(self, monkeypatch):+ monkeypatch.setattr(+ litellm,+ "model_cost",+ {"gpt-4o": {"deprecation_date": "2026-06-10"}},+ )+ router = _make_router(+ [+ {+ "model_name": "alias",+ "litellm_params": {"model": "openai/gpt-4o"},+ "model_info": {"id": "1"},+ }+ ]+ )++ snapshot = collect_model_deprecations(+ llm_router=router, warn_within_days=30, today=date(2026, 6, 1)+ )++ assert [m.litellm_model for m in snapshot.imminent] == ["gpt-4o"]++ def test_should_keep_both_dates_when_group_has_conflicting_dates(self, monkeypatch):+ monkeypatch.setattr(+ litellm,+ "model_cost",+ {"shared-model": {"deprecation_date": "2026-06-10"}},+ )+ router = _make_router(+ [+ {+ "model_name": "alias",+ "litellm_params": {"model": "shared-model"},+ "model_info": {"id": "1"},+ },+ {+ "model_name": "alias",+ "litellm_params": {"model": "shared-model"},+ "model_info": {"id": "2", "deprecation_date": "2027-01-01"},+ },+ ]+ )++ snapshot = collect_model_deprecations(+ llm_router=router, warn_within_days=30, today=date(2026, 6, 1)+ )++ assert len(snapshot.imminent) == 1+ assert len(snapshot.upcoming) == 1+def test_should_resolve_via_base_model(self, monkeypatch):today = date(2026, 6, 1)monkeypatch.setattr(diff --git a/tests/test_litellm/proxy/test_model_deprecations_endpoint.py b/tests/test_litellm/proxy/test_model_deprecations_endpoint.pynew file mode 100644index 00000000000..c942408bd14--- /dev/null+++ b/tests/test_litellm/proxy/test_model_deprecations_endpoint.py@@ -0,0 +1,77 @@+import os+import sys+from unittest.mock import MagicMock++import pytest+from fastapi.testclient import TestClient++sys.path.insert(0, os.path.abspath("../../.."))++import litellm+from litellm.proxy import proxy_server+from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth+from litellm.proxy.proxy_server import app++client = TestClient(app)+++def authenticated_client(monkeypatch):+ app.dependency_overrides[user_api_key_auth] = lambda: UserAPIKeyAuth(+ user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1234"+ )+ monkeypatch.setattr(+ litellm,+ "model_cost",+ {+ "sunset-model": {+ "deprecation_date": "2020-01-01",+ "litellm_provider": "openai",+ },+ "future-model": {+ "deprecation_date": "2099-01-01",+ "litellm_provider": "openai",+ },+ },+ )+ router = MagicMock()+ router.get_model_list.return_value = [+ {+ "model_name": "sunset-alias",+ "litellm_params": {"model": "sunset-model"},+ "model_info": {"id": "1"},+ },+ {+ "model_name": "future-alias",+ "litellm_params": {"model": "future-model"},+ "model_info": {"id": "2"},+ },+ ]+ monkeypatch.setattr(proxy_server, "llm_router", router)+ yield client+ app.dependency_overrides.pop(user_api_key_auth, None)+++def test_should_bucket_configured_models_by_urgency(authenticated_client):+ response = authenticated_client.get("/model/deprecations")++ assert response.status_code == 200+ payload = response.json()+ assert [m["model_name"] for m in payload["deprecated"]] == ["sunset-alias"]+ assert [m["model_name"] for m in payload["upcoming"]] == ["future-alias"]+ assert payload["imminent"] == []+ assert payload["warn_within_days"] == 30+ assert payload["deprecated"][0]["days_until_deprecation"] < 0+++def test_should_rebucket_with_warn_within_days_override(authenticated_client):+ response = authenticated_client.get(+ "/v1/model/deprecations", params={"warn_within_days": 40000}+ )++ assert response.status_code == 200+ payload = response.json()+ assert [m["model_name"] for m in payload["imminent"]] == ["future-alias"]+ assert payload["upcoming"] == []+ assert payload["warn_within_days"] == 40000diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex fa8731d7a16..93f1762a7fe 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -7814,6 +7814,48 @@ export interface paths {patch?: never;trace?: never;};+ "/model/deprecations": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /**+ * Model Deprecations+ * @description List models with known deprecation/sunset dates, bucketed by urgency.+ *+ * Reads `deprecation_date` metadata from `model_prices_and_context_window.json`+ * (and any per-deployment `model_info.deprecation_date` overrides) for the+ * models configured on this proxy.+ *+ * Parameters:+ * warn_within_days: Window (in days) used to bucket "imminent" models,+ * 30 by default.+ *+ * Returns:+ * A payload with three lists of `ModelDeprecationInfo` entries:+ *+ * - `deprecated`: deprecation date is in the past, so these requests may+ * fail at any time.+ * - `imminent`: deprecation date is within `warn_within_days` from today.+ * - `upcoming`: deprecation date is further out.+ *+ * Example:+ * ```shell+ * curl -X GET 'http://localhost:4000/model/deprecations' \+ * -H 'Authorization: Bearer sk-1234'+ * ```+ */+ get: operations["model_deprecations_model_deprecations_get"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/model/info": {parameters: {query?: never;@@ -17386,6 +17428,48 @@ export interface paths {patch?: never;trace?: never;};+ "/v1/model/deprecations": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /**+ * Model Deprecations+ * @description List models with known deprecation/sunset dates, bucketed by urgency.+ *+ * Reads `deprecation_date` metadata from `model_prices_and_context_window.json`+ * (and any per-deployment `model_info.deprecation_date` overrides) for the+ * models configured on this proxy.+ *+ * Parameters:+ * warn_within_days: Window (in days) used to bucket "imminent" models,+ * 30 by default.+ *+ * Returns:+ * A payload with three lists of `ModelDeprecationInfo` entries:+ *+ * - `deprecated`: deprecation date is in the past, so these requests may+ * fail at any time.+ * - `imminent`: deprecation date is within `warn_within_days` from today.+ * - `upcoming`: deprecation date is further out.+ *+ * Example:+ * ```shell+ * curl -X GET 'http://localhost:4000/model/deprecations' \+ * -H 'Authorization: Bearer sk-1234'+ * ```+ */+ get: operations["model_deprecations_v1_model_deprecations_get"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/v1/model/info": {parameters: {query?: never;@@ -21247,7 +21331,7 @@ export interface components {* @description Enum for alert types and management event types* @enum {string}*/- AlertType: "llm_exceptions" | "llm_too_slow" | "llm_requests_hanging" | "budget_alerts" | "spend_reports" | "failed_tracking_spend" | "db_exceptions" | "daily_reports" | "cooldown_deployment" | "new_model_added" | "outage_alerts" | "region_outage_alerts" | "fallback_reports" | "new_virtual_key_created" | "virtual_key_updated" | "virtual_key_deleted" | "new_team_created" | "team_updated" | "team_deleted" | "new_internal_user_created" | "internal_user_updated" | "internal_user_deleted";+ AlertType: "llm_exceptions" | "llm_too_slow" | "llm_requests_hanging" | "budget_alerts" | "spend_reports" | "failed_tracking_spend" | "db_exceptions" | "daily_reports" | "cooldown_deployment" | "new_model_added" | "model_deprecation_warnings" | "outage_alerts" | "region_outage_alerts" | "fallback_reports" | "new_virtual_key_created" | "virtual_key_updated" | "virtual_key_deleted" | "new_team_created" | "team_updated" | "team_deleted" | "new_internal_user_created" | "internal_user_updated" | "internal_user_deleted";/** AllowedVectorStoreIndexItem */AllowedVectorStoreIndexItem: {/** Index Name */@@ -28732,6 +28816,70 @@ export interface components {[key: string]: string | string[];};};+ /** ModelDeprecationInfo */+ ModelDeprecationInfo: {+ /**+ * Days Until Deprecation+ * @description Days remaining until the deprecation date. Negative if the model is already deprecated.+ */+ days_until_deprecation: number;+ /**+ * Deprecation Date+ * Format: date+ * @description The date (UTC) when the model becomes deprecated.+ */+ deprecation_date: string;+ /**+ * Litellm Model+ * @description The underlying litellm model string the deprecation date is sourced from.+ */+ litellm_model?: string | null;+ /**+ * Litellm Provider+ * @description The provider this model belongs to.+ */+ litellm_provider?: string | null;+ /**+ * Model Name+ * @description The public name of the model on the proxy (model_group).+ */+ model_name: string;+ /**+ * Status+ * @description 'deprecated' if the date has passed, 'imminent' if it falls within warn_within_days, 'upcoming' otherwise.+ * @enum {string}+ */+ status: "upcoming" | "imminent" | "deprecated";+ };+ /** ModelDeprecationResponse */+ ModelDeprecationResponse: {+ /**+ * Checked At+ * Format: date-time+ * @description UTC timestamp when the deprecation snapshot was generated.+ */+ checked_at: string;+ /**+ * Deprecated+ * @description Models whose deprecation date has already passed.+ */+ deprecated?: components["schemas"]["ModelDeprecationInfo"][];+ /**+ * Imminent+ * @description Models whose deprecation date is within warn_within_days from today and require immediate migration planning.+ */+ imminent?: components["schemas"]["ModelDeprecationInfo"][];+ /**+ * Upcoming+ * @description Models with a future deprecation date outside the warn window.+ */+ upcoming?: components["schemas"]["ModelDeprecationInfo"][];+ /**+ * Warn Within Days+ * @description The window (in days) used to bucket 'imminent' models.+ */+ warn_within_days: number;+ };/** ModelGroupInfoProxy */ModelGroupInfoProxy: {/** Configurable Clientside Auth Params */@@ -45860,6 +46008,37 @@ export interface operations {};};};+ model_deprecations_model_deprecations_get: {+ parameters: {+ query?: {+ warn_within_days?: number;+ };+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ModelDeprecationResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };model_info_v1_model_info_get: {parameters: {query?: {@@ -57641,6 +57820,37 @@ export interface operations {};};};+ model_deprecations_v1_model_deprecations_get: {+ parameters: {+ query?: {+ warn_within_days?: number;+ };+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ModelDeprecationResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };model_info_v1_v1_model_info_get: {parameters: {query?: {