Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

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

mateo-berri85f367b54527
diff --cc litellm/llms/bedrock/base_aws_llm.py
index 58478b2cb82,8cb15ad26ed..d7b7806a4a8
--- a/litellm/llms/bedrock/base_aws_llm.py
+++ b/litellm/llms/bedrock/base_aws_llm.py
@@@ -4,8 -4,8 +4,9 @@@ import jso
import os
import re
import urllib.parse
+from collections.abc import Callable
from datetime import datetime
+ from threading import Lock
from typing import (
TYPE_CHECKING,
Any,
@@@ -1041,8 -1056,12 +1052,12 @@@ class BaseAWSLLM
return sts_client.assume_role(**assume_role_params)
- def _extract_credentials_and_ttl(self, sts_response: dict) -> Tuple[Credentials, Optional[int]]:
+ def _extract_credentials_and_ttl(self, sts_response: dict) -> tuple[Credentials, int | None]:
- """Extract credentials and TTL from STS response."""
+ """Extract credentials and TTL from STS response.
+
+ The TTL carries the same safety margin as the non-IRSA assume path, so a cached entry is
+ never handed out close enough to expiry to die mid-request.
+ """
from botocore.credentials import Credentials
sts_credentials = sts_response["Credentials"]
diff --cc litellm/proxy/proxy_cli.py
index 5842c49953d,cdfacae0a5d..58b4ec88192
--- a/litellm/proxy/proxy_cli.py
+++ b/litellm/proxy/proxy_cli.py
@@@ -92,7 -93,73 +94,73 @@@ def _build_db_connection_url_params
return params
+ class DatabaseTimeoutSettings(BaseModel):
+ """The `general_settings` keys that bound how long a statement may hold locks.
+
+ Validated at the boundary so a mistyped value fails at startup with a clear
+ pydantic error instead of a TypeError deep inside URL assembly.
+ """
+
+ model_config = ConfigDict(extra="ignore")
+
+ database_statement_timeout: float | None = None
+ database_lock_timeout: float | None = None
+
+
+ def _pg_options_with_timeouts(
+ existing_options: str,
+ statement_timeout: float | None,
+ lock_timeout: float | None,
+ ) -> str:
+ """Return the Postgres ``options`` value carrying the configured timeouts.
+
+ Prisma has no URL parameter for `statement_timeout` / `lock_timeout`; they are
+ server settings delivered through the standard libpq ``options`` parameter as
+ ``-c <name>=<value>``. Values arrive in seconds (matching the sibling
+ ``database_*_timeout`` settings) and are emitted as integer milliseconds,
+ which is the unit Postgres assumes for a unit-less value.
+
+ Both settings are bounds on how long a single statement may hold its locks.
+ Without them a batch that outlives the Prisma client's HTTP read timeout keeps
+ running server side, holding row locks for as long as the database takes,
+ while the client has already given up; every later flush queues behind it.
+ The query engine's own transaction timeout cannot end that wait, because it
+ cannot interrupt a statement that is already executing.
+
+ Any ``options`` the operator already pinned on the URL is preserved, and a
+ setting they pinned there wins over the configured one. Postgres applies the
+ last occurrence of a setting, so a pinned one is honoured by not appending
+ ours at all; it is matched in every spelling the backend accepts
+ (``-c name=``, ``-cname=``, ``--name=``). The result is applied to
+ ``DATABASE_URL`` only, never ``DIRECT_URL``: that one serves migrations,
+ which legitimately run long and must not be cancelled mid-way.
+ """
+ configured = tuple(
+ f"-c {name}={int(seconds * 1000)}"
+ for name, seconds in (
+ ("statement_timeout", statement_timeout),
+ ("lock_timeout", lock_timeout),
+ )
+ if seconds is not None and not re.search(rf"(?:-c\s*|--){re.escape(name)}=", existing_options)
+ )
+ return " ".join(part for part in (existing_options, *configured) if part)
+
+
+ def _url_query_value(url: str | None, key: str) -> str:
+ """Return a single query-param value already present on ``url``, else ""."""
+ if not isinstance(url, str) or url == "":
+ return ""
+ return next(iter(urlparse.parse_qs(urlparse.urlparse(url).query).get(key) or ()), "")
+
+
+ def _with_query_value(url: str, key: str, value: str) -> str:
+ """Return ``url`` with a single query param replaced by ``value``."""
+ parsed = urlparse.urlparse(url)
+ pairs = tuple((k, v) for k, v in urlparse.parse_qsl(parsed.query) if k != key) + ((key, value),)
+ return urlparse.urlunparse(parsed._replace(query=urlparse.urlencode(pairs)))
+
+
-def append_query_params(url: Optional[str], params: dict) -> str:
+def append_query_params(url: str | None, params: dict) -> str:
from litellm._logging import verbose_proxy_logger
verbose_proxy_logger.debug(f"url: {url}")
@@@ -1003,11 -1070,13 +1071,13 @@@ def run_server
db_connection_pool_limit = 100
# Starts optional due to config fallback checks; guaranteed non-None before use.
- db_connection_timeout: Optional[Union[int, float]] = 60
- db_connect_timeout: Optional[Union[int, float]] = None
- db_socket_timeout: Optional[Union[int, float]] = None
+ db_connection_timeout: int | float | None = 60
+ db_connect_timeout: int | float | None = None
+ db_socket_timeout: int | float | None = None
db_disable_prepared_statements: bool = False
- db_extra_connection_params: Optional[dict] = None
+ db_extra_connection_params: dict | None = None
+ db_statement_timeout: float | None = None
+ db_lock_timeout: float | None = None
general_settings = {}
### GET DB TOKEN FOR IAM AUTH ###
diff --cc litellm/proxy/proxy_server.py
index b310b8e1dbf,04161d775f8..901ca39326b
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@@ -3823,10 -3836,11 +3827,11 @@@ class ProxyConfig
"""
def __init__(self) -> None:
- self.config: Dict[str, Any] = {}
- self._last_semantic_filter_config: Optional[Dict[str, Any]] = None
- self._last_hashicorp_vault_config: Optional[Dict[str, Any]] = None
- self.worker_registry: List["WorkerRegistryEntry"] = []
+ self.config: dict[str, Any] = {}
+ self._last_semantic_filter_config: dict[str, Any] | None = None
+ self._last_hashicorp_vault_config: dict[str, Any] | None = None
+ self.worker_registry: list[WorkerRegistryEntry] = []
+ self.config_sync_subscriber: ConfigSyncSubscriber | None = None
def is_yaml(self, config_file_path: str) -> bool:
if not os.path.isfile(config_file_path):
@@@ -6199,6 -6221,38 +6204,38 @@@
return still_desired_ids
+ def start_config_sync_subscriber(
+ self,
+ prisma_client: PrismaClient,
+ proxy_logging_obj: ProxyLogging,
- redis_cache: Optional[RedisCache],
++ redis_cache: RedisCache | None,
+ ) -> None:
+ if redis_cache is None or self.config_sync_subscriber is not None:
+ return
+
+ async def _resync_config_from_db() -> None:
+ await self.add_deployment(prisma_client=prisma_client, proxy_logging_obj=proxy_logging_obj)
+
+ async def _resync_credentials_from_db() -> None:
+ await self.get_credentials(prisma_client=prisma_client)
+
+ subscriber = ConfigSyncSubscriber(
+ redis_cache=redis_cache,
+ resync_callbacks=(_resync_config_from_db, _resync_credentials_from_db),
+ )
+ self.config_sync_subscriber = subscriber
+ subscriber.start()
+
+ async def stop_config_sync_subscriber(self) -> None:
+ subscriber = self.config_sync_subscriber
+ if subscriber is None:
+ return
+ self.config_sync_subscriber = None
+ try:
+ await subscriber.stop()
+ except Exception as e:
+ verbose_proxy_logger.error(f"Error stopping config sync subscriber: {e}")
+
async def _init_non_llm_objects_in_db(self, prisma_client: PrismaClient):
"""
Use this to read non-llm objects from the db and initialize them
diff --cc litellm/proxy/utils.py
index 40db863de5d,e1b8f89149b..68d75384452
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@@ -2964,12 -2974,17 +2967,17 @@@ async def get_config_param(prisma_clien
return row
+ async def evict_config_param(param_name: str) -> None:
+ await litellm_config_cache.async_delete_cache(_config_cache_key(param_name))
+
+
async def invalidate_config_param(param_name: str) -> None:
"""Evict from both cache layers; call after every LiteLLM_Config write."""
- await litellm_config_cache.async_delete_cache(_config_cache_key(param_name))
+ await evict_config_param(param_name)
+ await publish_config_param_change(param_name)
-async def prefetch_config_params(prisma_client: Any, param_names: List[str]) -> None:
+async def prefetch_config_params(prisma_client: Any, param_names: list[str]) -> None:
"""Batch-load LiteLLM_Config rows into the cache with one find_many."""
if not param_names:
return
diff --cc litellm/repositories/credentials_repository.py
index ccb1f9b2467,8e4b9ac0be7..c7c213fb78b
--- a/litellm/repositories/credentials_repository.py
+++ b/litellm/repositories/credentials_repository.py
@@@ -6,9 -6,10 +6,10 @@@ credential values is the caller's respo
so reads return the stored values verbatim.
"""
-from typing import Any, Dict, Optional
+from typing import Any
from litellm.models.credentials import CredentialItem
+ from litellm.proxy.common_utils.config_sync_pubsub import wrap_table_actions_for_config_sync
class CredentialsRepository:
@@@ -25,10 -26,13 +26,13 @@@
@property
def table(self) -> Any:
- return self.prisma_client.db.litellm_credentialstable
+ return wrap_table_actions_for_config_sync(
+ actions=self.prisma_client.db.litellm_credentialstable,
+ table_name="litellm_credentialstable",
+ )
@staticmethod
- def _to_model(record: Any) -> Optional[CredentialItem]:
+ def _to_model(record: Any) -> CredentialItem | None:
if record is None:
return None
data = record.dict() if hasattr(record, "dict") else dict(record)
diff --cc litellm/repositories/model_repository.py
index 26b782be33d,50a50cc60d6..d4b6a40d829
--- a/litellm/repositories/model_repository.py
+++ b/litellm/repositories/model_repository.py
@@@ -3,9 -3,11 +3,10 @@@ Model repository for database operation
"""
import json
-from typing import Any, Dict, List, Optional, Type
+from typing import Any
from litellm.models.model import LiteLLM_ProxyModelTable
-from litellm.repositories.base_repository import BaseRepository
+ from litellm.proxy.common_utils.config_sync_pubsub import wrap_table_actions_for_config_sync
from litellm.proxy.common_utils.encrypt_decrypt_utils import (
decrypt_value_helper,
encrypt_value_helper,
@@@ -22,13 -23,16 +23,16 @@@ class ModelRepository(BaseRepository[Li
@property
def table(self) -> Any:
- return self.prisma_client.db.litellm_proxymodeltable
+ return wrap_table_actions_for_config_sync(
+ actions=self.prisma_client.db.litellm_proxymodeltable,
+ table_name="litellm_proxymodeltable",
+ )
@property
- def model_class(self) -> Type[LiteLLM_ProxyModelTable]:
+ def model_class(self) -> type[LiteLLM_ProxyModelTable]:
return LiteLLM_ProxyModelTable
- def _encrypt_litellm_params(self, litellm_params: Dict[str, Any]) -> Dict[str, Any]:
+ def _encrypt_litellm_params(self, litellm_params: dict[str, Any]) -> dict[str, Any]:
"""Encrypt sensitive values in litellm_params."""
encrypted = {}
for key, value in litellm_params.items():
diff --cc litellm/router.py
index 722dbf75509,1cc9361a76b..37190bdbf38
--- a/litellm/router.py
+++ b/litellm/router.py
@@@ -2924,22 -2948,16 +2924,16 @@@ class Router
) -> None:
"""
Adds/updates to kwargs:
- - num_retries
- litellm_trace_id
- metadata
+
+ num_retries is deliberately left as the caller passed it, with no default filled in.
+ async_function_with_retries resolves the router/global default itself, and it can only
+ honour the precedence request > deployment litellm_params > litellm_settings while an
+ absent num_retries still means "the caller did not ask for one".
"""
- # Normalise an explicit num_retries=None to the router default here (dict.get()
- # only falls back when the key is absent, not when its value is None), then to 0
- # if the router default is itself None - mirroring the guard in
- # async_function_with_retries, which remains the safety net for paths that bypass
- # this setter.
- _req_num_retries = kwargs.get("num_retries")
- if _req_num_retries is not None:
- kwargs["num_retries"] = _req_num_retries
- else:
- kwargs["num_retries"] = self.num_retries if self.num_retries is not None else 0
kwargs.setdefault("litellm_trace_id", str(uuid.uuid4()))
- model_group_alias: Optional[str] = None
+ model_group_alias: str | None = None
if self._get_model_from_alias(model=model):
model_group_alias = model
kwargs.setdefault(metadata_variable_name, {}).update(
@@@ -6465,8 -6490,9 +6453,9 @@@
content_policy_fallbacks = kwargs.pop("content_policy_fallbacks", self.content_policy_fallbacks)
# Support per-request model_group_retry_policy override (from key/team settings)
model_group_retry_policy = kwargs.pop("model_group_retry_policy", self.model_group_retry_policy)
- model_group: Optional[str] = kwargs.get("model")
- request_num_retries: Optional[int] = kwargs.pop("num_retries", None)
+ model_group: str | None = kwargs.get("model")
- num_retries = kwargs.pop("num_retries", None)
++ request_num_retries: int | None = kwargs.pop("num_retries", None)
+ num_retries = request_num_retries
if num_retries is None:
# Fall back to the router setting (then 0) so the comparisons below never
# hit `None > int`, which would mask the real upstream error with a TypeError.