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]

added the env flag

shivama7f516397687
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md
index 8dbebad884e..dde39bbc0b3 100644
--- a/docs/my-website/docs/proxy/config_settings.md
+++ b/docs/my-website/docs/proxy/config_settings.md
@@ -775,6 +775,7 @@ router_settings:
| LITELLM_HOSTED_UI | URL of the hosted UI for LiteLLM
| LITELLM_UI_API_DOC_BASE_URL | Optional override for the API Reference base URL (used in sample code/docs) when the admin UI runs on a different host than the proxy. Defaults to `PROXY_BASE_URL` when unset.
| LITELLM_UI_PATH | Path to directory for Admin UI files. Used when running with read-only filesystem (e.g., Kubernetes). Default is `/var/lib/litellm/ui` in Docker.
+| LITELLM_UI_SESSION_DURATION | Duration for UI login session (username/password, SSO). Format: "30s", "30m", "24h", "7d". Applies to both default and EXPERIMENTAL_UI_LOGIN flows. Default is "24h"
| 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).
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 6e42f2c1ea5..f949046e4d3 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -12,6 +12,12 @@ warnings.filterwarnings(
### INIT VARIABLES #########################
import threading
import os
+
+# Load .env before any other litellm imports so env vars (e.g. LITELLM_UI_SESSION_DURATION) are available
+import dotenv as _dotenv
+
+_dotenv.load_dotenv()
+
from typing import (
Callable,
List,
@@ -74,12 +80,9 @@ from litellm.constants import (
DEFAULT_ALLOWED_FAILS,
)
import httpx
-import dotenv
# register_async_client_cleanup is lazy-loaded and called on first access
litellm_mode = os.getenv("LITELLM_MODE", "DEV") # "PRODUCTION", "DEV"
-if litellm_mode == "DEV":
- dotenv.load_dotenv()
####################################################
diff --git a/litellm/constants.py b/litellm/constants.py
index b1a0021bcc6..41dce4c587a 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1314,6 +1314,11 @@ CLI_JWT_EXPIRATION_HOURS = int(
or 24
)
+########################### UI SESSION DURATION ###########################
+# Duration for UI login session (username/password, SSO). Format: "30s", "30m", "24h", "7d"
+# Applies to both default and EXPERIMENTAL_UI_LOGIN flows
+LITELLM_UI_SESSION_DURATION = os.getenv("LITELLM_UI_SESSION_DURATION", "24h")
+
########################### DB CRON JOB NAMES ###########################
DB_SPEND_UPDATE_JOB_NAME = "db_spend_update_job"
PROMETHEUS_EMIT_BUDGET_METRICS_JOB_NAME = "prometheus_emit_budget_metrics"
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index 500a39d9455..25ea9bb4f86 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -23,12 +23,14 @@ from litellm.caching.dual_cache import LimitedSizeOrderedDict
from litellm.constants import (
CLI_JWT_EXPIRATION_HOURS,
CLI_JWT_TOKEN_NAME,
+ LITELLM_UI_SESSION_DURATION,
DEFAULT_ACCESS_GROUP_CACHE_TTL,
DEFAULT_IN_MEMORY_TTL,
DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL,
DEFAULT_MAX_RECURSE_DEPTH,
EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE,
)
+from litellm.litellm_core_utils.duration_parser import duration_in_seconds
from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider
from litellm.proxy._types import (
RBAC_ROLES,
@@ -1884,8 +1886,9 @@ class ExperimentalUIJWTToken:
if user_info.user_role is None:
raise Exception("User role is required for experimental UI login")
- # Calculate expiration time (10 minutes from now)
- expiration_time = get_utc_datetime() + timedelta(minutes=10)
+ # Calculate expiration time from LITELLM_UI_SESSION_DURATION (default 24h)
+ session_duration_seconds = duration_in_seconds(LITELLM_UI_SESSION_DURATION)
+ expiration_time = get_utc_datetime() + timedelta(seconds=session_duration_seconds)
# Format the expiration time as ISO 8601 string
expires = expiration_time.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "+00:00"
diff --git a/litellm/proxy/auth/login_utils.py b/litellm/proxy/auth/login_utils.py
index 4df773dec2b..c7e22516fe5 100644
--- a/litellm/proxy/auth/login_utils.py
+++ b/litellm/proxy/auth/login_utils.py
@@ -12,7 +12,7 @@ from typing import Literal, Optional, cast
from fastapi import HTTPException
import litellm
-from litellm.constants import LITELLM_PROXY_ADMIN_NAME
+from litellm.constants import LITELLM_PROXY_ADMIN_NAME, LITELLM_UI_SESSION_DURATION
from litellm.proxy._types import (
LiteLLM_UserTable,
LitellmUserRoles,
@@ -178,7 +178,7 @@ async def authenticate_user( # noqa: PLR0915
request_type="key",
**{
"user_role": LitellmUserRoles.PROXY_ADMIN,
- "duration": "24hr",
+ "duration": LITELLM_UI_SESSION_DURATION,
"key_max_budget": litellm.max_ui_session_budget,
"models": [],
"aliases": {},
@@ -264,7 +264,7 @@ async def authenticate_user( # noqa: PLR0915
request_type="key",
**{ # type: ignore
"user_role": user_role,
- "duration": "24hr",
+ "duration": LITELLM_UI_SESSION_DURATION,
"key_max_budget": litellm.max_ui_session_budget,
"models": [],
"aliases": {},
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index 5a1b31aebb8..84e945e8883 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -25,6 +25,7 @@ from litellm._logging import verbose_proxy_logger
from litellm._uuid import uuid
from litellm.caching import DualCache
from litellm.constants import (
+ LITELLM_UI_SESSION_DURATION,
MAX_SPENDLOG_ROWS_TO_QUERY,
MICROSOFT_USER_DISPLAY_NAME_ATTRIBUTE,
MICROSOFT_USER_EMAIL_ATTRIBUTE,
@@ -2237,7 +2238,7 @@ class SSOAuthenticationHandler:
# User might not be already created on first generation of key
# But if it is, we want their models preferences
default_ui_key_values: Dict[str, Any] = {
- "duration": "24hr",
+ "duration": LITELLM_UI_SESSION_DURATION,
"key_max_budget": litellm.max_ui_session_budget,
"aliases": {},
"config": {},
diff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.py
index 1d8d1be58c7..fb2f427e443 100644
--- a/tests/test_litellm/proxy/auth/test_auth_checks.py
+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py
@@ -108,11 +108,40 @@ def test_get_experimental_ui_login_jwt_auth_token_valid(valid_sso_user_defined_v
assert token_data["models"] == ["gpt-3.5-turbo"]
assert token_data["max_budget"] == litellm.max_ui_session_budget
- # Verify expiration time is set and valid
+ # Verify expiration time is set and valid (uses LITELLM_UI_SESSION_DURATION)
+ from litellm.constants import LITELLM_UI_SESSION_DURATION
+ from litellm.litellm_core_utils.duration_parser import duration_in_seconds
+
assert "expires" in token_data
expires = datetime.fromisoformat(token_data["expires"].replace("Z", "+00:00"))
- assert expires > get_utc_datetime()
- assert expires <= get_utc_datetime() + timedelta(minutes=10)
+ session_duration_seconds = duration_in_seconds(LITELLM_UI_SESSION_DURATION)
+ now = get_utc_datetime()
+ # Allow 2 second buffer for test execution timing
+ assert expires > now
+ assert expires <= now + timedelta(seconds=session_duration_seconds + 2)
+
+
+def test_get_experimental_ui_login_jwt_auth_token_respects_session_duration(
+ valid_sso_user_defined_values, monkeypatch
+):
+ """Test that LITELLM_UI_SESSION_DURATION controls token expiration"""
+ from litellm.proxy.auth import auth_checks
+
+ monkeypatch.setattr(auth_checks, "LITELLM_UI_SESSION_DURATION", "10m")
+
+ token = ExperimentalUIJWTToken.get_experimental_ui_login_jwt_auth_token(
+ valid_sso_user_defined_values
+ )
+ decrypted_token = decrypt_value_helper(
+ token, key="ui_hash_key", exception_type="debug"
+ )
+ assert decrypted_token is not None
+ token_data = json.loads(decrypted_token)
+ expires = datetime.fromisoformat(token_data["expires"].replace("Z", "+00:00"))
+ now = get_utc_datetime()
+ # Should expire in ~10 minutes (allow 2 second buffer)
+ assert expires > now + timedelta(minutes=9)
+ assert expires <= now + timedelta(minutes=10, seconds=2)
def test_get_experimental_ui_login_jwt_auth_token_invalid(