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
Merge branch 'main' into litellm_fix-virtual-key-grace-period
Harshit Jain56b53cb502ff
diff --cc docs/my-website/docs/proxy/config_settings.mdindex 03cf665b3c8,ac554b09174..5e3f56c4206--- a/docs/my-website/docs/proxy/config_settings.md+++ b/docs/my-website/docs/proxy/config_settings.md@@@ -765,9 -769,10 +769,11 @@@ router_settings| LITELM_ENVIRONMENT | Environment of LiteLLM Instance, used by logging services. Currently only used by DeepEval.| LITELLM_KEY_ROTATION_ENABLED | Enable auto-key rotation for LiteLLM (boolean). Default is false.| LITELLM_KEY_ROTATION_CHECK_INTERVAL_SECONDS | Interval in seconds for how often to run job that auto-rotates keys. Default is 86400 (24 hours).+| LITELLM_KEY_ROTATION_GRACE_PERIOD | Duration to keep old key valid after rotation (e.g. "24h", "2d"). Default is empty (immediate revoke). Used for scheduled rotations and as fallback when not specified in regenerate request.| LITELLM_LICENSE | License key for LiteLLM usage+ | LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS | Set to `True` to use the local bundled Anthropic beta headers config only, disabling remote fetching. Default is `False`| LITELLM_LOCAL_MODEL_COST_MAP | Local configuration for model cost mapping in LiteLLM+ | LITELLM_LOCAL_POLICY_TEMPLATES | When set to "true", uses local backup policy templates instead of fetching from GitHub. Policy templates are fetched from https://raw.githubusercontent.com/BerriAI/litellm/main/policy_templates.json by default, with automatic fallback to local backup on failure| LITELLM_LOG | Enable detailed logging for LiteLLM| LITELLM_MODEL_COST_MAP_URL | URL for fetching model cost map data. Default is https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json| LITELLM_LOG_FILE | File path to write LiteLLM logs to. When set, logs will be written to both console and the specified filediff --cc litellm/proxy/management_endpoints/key_management_endpoints.pyindex e8a1af27978,17cabb69cb2..9dcc25e7a87--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@@ -3182,67 -3181,61 +3187,122 @@@ def get_new_token(data: Optional[Regenereturn new_token+async def _insert_deprecated_key(+ prisma_client: "PrismaClient",+ old_token_hash: str,+ new_token_hash: str,+ grace_period: Optional[str],+) -> None:+ """+ Insert old key into deprecated table so it remains valid during grace period.++ Uses upsert to handle concurrent rotations gracefully.++ Parameters:+ prisma_client: DB client+ old_token_hash: Hash of the old key being rotated out+ new_token_hash: Hash of the new replacement key+ grace_period: Duration string (e.g. "24h", "2d") or None/empty for immediate revoke+ """+ grace_period_value = grace_period or os.getenv(+ "LITELLM_KEY_ROTATION_GRACE_PERIOD", ""+ )+ if not grace_period_value:+ return++ try:+ grace_seconds = duration_in_seconds(grace_period_value)+ except ValueError:+ verbose_proxy_logger.warning(+ "Invalid grace_period format: %s. Expected format like '24h', '2d'.",+ grace_period_value,+ )+ return++ if grace_seconds <= 0:+ return++ try:+ revoke_at = datetime.now(timezone.utc) + timedelta(seconds=grace_seconds)+ await prisma_client.db.litellm_deprecatedverificationtoken.upsert(+ where={"token": old_token_hash},+ data={+ "create": {+ "token": old_token_hash,+ "active_token_id": new_token_hash,+ "revoke_at": revoke_at,+ },+ "update": {+ "active_token_id": new_token_hash,+ "revoke_at": revoke_at,+ },+ },+ )+ verbose_proxy_logger.debug(+ "Deprecated key retained for %s (revoke_at: %s)",+ grace_period_value,+ revoke_at,+ )+ except Exception as deprecated_err:+ verbose_proxy_logger.warning(+ "Failed to insert deprecated key for grace period: %s",+ deprecated_err,+ )+ async def _execute_virtual_key_regeneration(+ *,+ prisma_client: PrismaClient,+ key_in_db: LiteLLM_VerificationToken,+ hashed_api_key: str,+ key: str,+ data: Optional[RegenerateKeyRequest],+ user_api_key_dict: UserAPIKeyAuth,+ litellm_changed_by: Optional[str],+ user_api_key_cache: DualCache,+ proxy_logging_obj: ProxyLogging,+ ) -> GenerateKeyResponse:+ """Generate new token, update DB, invalidate cache, and return response."""+ from litellm.proxy.proxy_server import hash_token++ new_token = get_new_token(data=data)+ new_token_hash = hash_token(new_token)+ new_token_key_name = f"sk-...{new_token[-4:]}"+ update_data = {"token": new_token_hash, "key_name": new_token_key_name}++ non_default_values = {}+ if data is not None:+ non_default_values = await prepare_key_update_data(+ data=data, existing_key_row=key_in_db+ )+ verbose_proxy_logger.debug("non_default_values: %s", non_default_values)+ update_data.update(non_default_values)+ update_data = prisma_client.jsonify_object(data=update_data)++ updated_token = await prisma_client.db.litellm_verificationtoken.update(+ where={"token": hashed_api_key},+ data=update_data, # type: ignore+ )+ updated_token_dict = dict(updated_token) if updated_token is not None else {}+ updated_token_dict["key"] = new_token+ updated_token_dict["token_id"] = updated_token_dict.pop("token")++ if hashed_api_key or key:+ await _delete_cache_key_object(+ hashed_token=hash_token(key),+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )++ response = GenerateKeyResponse(**updated_token_dict)+ asyncio.create_task(+ KeyManagementEventHooks.async_key_rotated_hook(+ data=data,+ existing_key_row=key_in_db,+ response=response,+ user_api_key_dict=user_api_key_dict,+ litellm_changed_by=litellm_changed_by,+ )+ )+ return response@router.post(@@@ -3414,78 -3406,32 +3474,84 @@@ async def regenerate_key_fn( # noqa: P)verbose_proxy_logger.debug("key_in_db: %s", _key_in_db)+ new_token = get_new_token(data=data)++ new_token_hash = hash_token(new_token)+ new_token_key_name = f"sk-...{new_token[-4:]}"++ # Prepare the update data+ update_data = {+ "token": new_token_hash,+ "key_name": new_token_key_name,+ }++ non_default_values = {}+ if data is not None:+ # Update with any provided parameters from GenerateKeyRequest+ non_default_values = await prepare_key_update_data(+ data=data, existing_key_row=_key_in_db+ )+ verbose_proxy_logger.debug("non_default_values: %s", non_default_values)++ update_data.update(non_default_values)+ update_data = prisma_client.jsonify_object(data=update_data)++ # If grace period set, insert deprecated key so old key remains valid+ await _insert_deprecated_key(+ prisma_client=prisma_client,+ old_token_hash=hashed_api_key,+ new_token_hash=new_token_hash,+ grace_period=data.grace_period if data else None,+ )++ # Update the token in the database+ updated_token = await prisma_client.db.litellm_verificationtoken.update(+ where={"token": hashed_api_key},+ data=update_data, # type: ignore+ )++ updated_token_dict = {}+ if updated_token is not None:+ updated_token_dict = dict(updated_token)++ updated_token_dict["key"] = new_token+ updated_token_dict["token_id"] = updated_token_dict.pop("token")++ ### 3. remove existing key entry from cache+ ######################################################################++ if hashed_api_key or key:+ await _delete_cache_key_object(+ hashed_token=hash_token(key),+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+ # Normalize litellm_changed_by: if it's a Header object or not a string, convert to None+ if litellm_changed_by is not None and not isinstance(litellm_changed_by, str):+ litellm_changed_by = None- response = GenerateKeyResponse(- **updated_token_dict,+ # Save the old key record to deleted table before regeneration.+ # This preserves key_alias and team_id metadata for historical spend records.+ # If this fails, abort the regeneration to avoid permanently losing the+ # old hash→metadata mapping.+ await _persist_deleted_verification_tokens(+ keys=[_key_in_db],+ prisma_client=prisma_client,+ user_api_key_dict=user_api_key_dict,+ litellm_changed_by=litellm_changed_by,)- verbose_proxy_logger.info(- "Key regeneration completed: key_alias=%s",- getattr(_key_in_db, "key_alias", None),- )- asyncio.create_task(- KeyManagementEventHooks.async_key_rotated_hook(- data=data,- existing_key_row=_key_in_db,- response=response,- user_api_key_dict=user_api_key_dict,- litellm_changed_by=litellm_changed_by,- )+ return await _execute_virtual_key_regeneration(+ prisma_client=prisma_client,+ key_in_db=_key_in_db,+ hashed_api_key=hashed_api_key,+ key=key,+ data=data,+ user_api_key_dict=user_api_key_dict,+ litellm_changed_by=litellm_changed_by,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,)-- return responseexcept Exception as e:verbose_proxy_logger.exception("Error regenerating key: %s", e)raise handle_exception_on_proxy(e)diff --cc litellm/proxy/utils.pyindex bb95b98da66,6c8db8d7d99..1c2a6d378fc--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@@ -76,9 -76,11 +76,12 @@@ from litellm importfrom litellm._logging import verbose_proxy_loggerfrom litellm._service_logger import ServiceLogging, ServiceTypesfrom litellm.caching.caching import DualCache, RedisCache+from litellm.caching.dual_cache import LimitedSizeOrderedDictfrom litellm.exceptions import RejectedRequestError- from litellm.integrations.custom_guardrail import CustomGuardrail+ from litellm.integrations.custom_guardrail import (+ CustomGuardrail,+ ModifyResponseException,+ )from litellm.integrations.custom_logger import CustomLoggerfrom litellm.integrations.SlackAlerting.slack_alerting import SlackAlertingfrom litellm.integrations.SlackAlerting.utils import _add_langfuse_trace_id_to_alert