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
style: apply black formatting
Krrish Dholakiad05335591a58
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.pyindex 1d92a9da073..723b142dfad 100644--- a/litellm/integrations/prometheus.py+++ b/litellm/integrations/prometheus.py@@ -51,6 +51,7 @@ if TYPE_CHECKING:else:AsyncIOScheduler = Any+class PrometheusLogger(CustomLogger):# Class variables or attributes@@ -991,9 +992,7 @@ class PrometheusLogger(CustomLogger):amount: float = 1.0,) -> None:_labels = prometheus_label_factory(- supported_enum_labels=self.get_labels_for_metric(- metric_name=metric_name- ),+ supported_enum_labels=self.get_labels_for_metric(metric_name=metric_name),enum_values=enum_values,label_context=label_context,)@@ -1118,7 +1117,9 @@ class PrometheusLogger(CustomLogger):user_api_key = hash_token(user_api_key)- label_context = PrometheusLabelFactoryContext(enum_values) #amortized per request.+ label_context = PrometheusLabelFactoryContext(+ enum_values+ ) # amortized per request.# increment total LLM requests and spend metricself._increment_top_level_request_and_spend_metrics(@@ -3490,7 +3491,9 @@ def _prometheus_labels_from_context(}if UserAPIKeyLabelNames.END_USER.value in filtered_labels:- filtered_labels[UserAPIKeyLabelNames.END_USER.value] = ctx.get_resolved_end_user()+ filtered_labels[UserAPIKeyLabelNames.END_USER.value] = (+ ctx.get_resolved_end_user()+ )for sk, val in ctx._custom_by_sanitized_key.items():if sk in supported_enum_labels:diff --git a/litellm/integrations/prometheus_helpers/__init__.py b/litellm/integrations/prometheus_helpers/__init__.pyindex 34f4855863e..784ab524dd5 100644--- a/litellm/integrations/prometheus_helpers/__init__.py+++ b/litellm/integrations/prometheus_helpers/__init__.py@@ -51,8 +51,7 @@ class PrometheusLabelFactoryContext:self.enum_values = enum_valuesenum_dict = enum_values.model_dump()self._sanitized_enum: Dict[str, Optional[str]] = {- k: _sanitize_prometheus_label_value(v)- for k, v in enum_dict.items()+ k: _sanitize_prometheus_label_value(v) for k, v in enum_dict.items()}self._custom_by_sanitized_key: Dict[str, Optional[str]] = {}if enum_values.custom_metadata_labels is not None:diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.pyindex 7b4aa7a3f10..41618c72627 100644--- a/litellm/integrations/websearch_interception/handler.py+++ b/litellm/integrations/websearch_interception/handler.py@@ -847,7 +847,9 @@ class WebSearchInterceptionLogger(CustomLogger):kwargs_for_followup = self._prepare_followup_kwargs(kwargs)if logging_obj is not None:- agentic_params = logging_obj.model_call_details.get("agentic_loop_params", {})+ agentic_params = logging_obj.model_call_details.get(+ "agentic_loop_params", {}+ )full_model_name = agentic_params.get("model", model)verbose_logger.debug("WebSearchInterception: Built anthropic request patch "diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.pyindex 3fd913958da..888999504fe 100644--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py@@ -684,7 +684,7 @@ def generic_cost_per_token( # noqa: PLR0915- cache_creation- image_tokens)- # Clamp to zero: inconsistent streaming usage+ # Clamp to zero: inconsistent streaming usageif text_tokens < 0:text_tokens = 0prompt_tokens_details["text_tokens"] = text_tokensdiff --git a/litellm/llms/anthropic/experimental_pass_through/messages/agentic_streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/messages/agentic_streaming_iterator.pyindex 1f14886ca8e..d0780c82d06 100644--- a/litellm/llms/anthropic/experimental_pass_through/messages/agentic_streaming_iterator.py+++ b/litellm/llms/anthropic/experimental_pass_through/messages/agentic_streaming_iterator.py@@ -216,9 +216,11 @@ class AgenticAnthropicStreamingIterator:return[- f"{b.get('type')}({b.get('name', '')})"- if b.get("type") == "tool_use"- else b.get("type")+ (+ f"{b.get('type')}({b.get('name', '')})"+ if b.get("type") == "tool_use"+ else b.get("type")+ )for b in rebuilt.get("content", [])]diff --git a/litellm/llms/github_copilot/authenticator.py b/litellm/llms/github_copilot/authenticator.pyindex f4698861edc..9de2987b9f6 100644--- a/litellm/llms/github_copilot/authenticator.py+++ b/litellm/llms/github_copilot/authenticator.py@@ -294,9 +294,7 @@ class Authenticator:access_token_url = os.getenv("GITHUB_COPILOT_ACCESS_TOKEN_URL", DEFAULT_GITHUB_ACCESS_TOKEN_URL)- client_id = os.getenv(- "GITHUB_COPILOT_CLIENT_ID", DEFAULT_GITHUB_CLIENT_ID- )+ client_id = os.getenv("GITHUB_COPILOT_CLIENT_ID", DEFAULT_GITHUB_CLIENT_ID)for attempt in range(max_attempts):try:diff --git a/litellm/passthrough/utils.py b/litellm/passthrough/utils.pyindex 5dde13f0078..d39a0dda152 100644--- a/litellm/passthrough/utils.py+++ b/litellm/passthrough/utils.py@@ -79,7 +79,9 @@ class BasePassthroughUtils:for header_name, header_value in request_headers.items():if header_name.lower().startswith(PASS_THROUGH_HEADER_PREFIX):# Strip the 'x-pass-' prefix and normalize to lowercase- actual_header_name = header_name[len(PASS_THROUGH_HEADER_PREFIX) :].lower()+ actual_header_name = header_name[+ len(PASS_THROUGH_HEADER_PREFIX) :+ ].lower()if actual_header_name in _PASS_THROUGH_PROTECTED_HEADERS or any(actual_header_name.startswith(p)for p in _PASS_THROUGH_PROTECTED_HEADER_PREFIXESdiff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex d245ec53ece..e19d04a2609 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -3126,9 +3126,7 @@ async def _virtual_key_max_budget_alert_check(alert_email_config: Optional[Dict[str, List[str]]] = (_merge_budget_alert_email_configs(global_cfg=litellm.default_key_max_budget_alert_emails,- per_key_cfg=(valid_token.metadata or {}).get(- "max_budget_alert_emails"- ),+ per_key_cfg=(valid_token.metadata or {}).get("max_budget_alert_emails"),))@@ -3138,7 +3136,9 @@ async def _virtual_key_max_budget_alert_check((int(k) for k in alert_email_config if k.isdigit()),default=None,)- if min_pct is None or valid_token.spend < valid_token.max_budget * (min_pct / 100.0):+ if min_pct is None or valid_token.spend < valid_token.max_budget * (+ min_pct / 100.0+ ):returncall_info = CallInfo(@@ -3164,8 +3164,7 @@ async def _virtual_key_max_budget_alert_check(else:# Old path: existing single 80% threshold — completely unchangedalert_threshold = (- valid_token.max_budget- * EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE+ valid_token.max_budget * EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE)if (diff --git a/litellm/proxy/db/db_transaction_queue/adaptive_router_update_queue.py b/litellm/proxy/db/db_transaction_queue/adaptive_router_update_queue.pyindex d1e275a076d..7f5d9f78541 100644--- a/litellm/proxy/db/db_transaction_queue/adaptive_router_update_queue.py+++ b/litellm/proxy/db/db_transaction_queue/adaptive_router_update_queue.py@@ -132,7 +132,9 @@ class AdaptiveRouterUpdateQueue:"update": {"alpha": {"increment": payload["delta_alpha"]},"beta": {"increment": payload["delta_beta"]},- "total_samples": {"increment": int(payload["samples_added"])},+ "total_samples": {+ "increment": int(payload["samples_added"])+ },},},)diff --git a/litellm/proxy/health_check.py b/litellm/proxy/health_check.pyindex e0664703d28..7d67750c78f 100644--- a/litellm/proxy/health_check.py+++ b/litellm/proxy/health_check.py@@ -306,7 +306,9 @@ def _health_check_deployment_is_wildcard(litellm_params: dict) -> bool:return "*" in _deployment_model_string_for_health_check(litellm_params)-def _resolve_health_check_max_tokens(model_info: dict, litellm_params: dict) -> Optional[int]:+def _resolve_health_check_max_tokens(+ model_info: dict, litellm_params: dict+) -> Optional[int]:"""Pick max_tokens for the health check request.@@ -341,10 +343,7 @@ def _resolve_health_check_max_tokens(model_info: dict, litellm_params: dict) ->return int(tokens_reasoning)if not is_reasoning and tokens_non_reasoning is not None:return int(tokens_non_reasoning)- if (- is_reasoning- and BACKGROUND_HEALTH_CHECK_MAX_TOKENS_REASONING is not None- ):+ if is_reasoning and BACKGROUND_HEALTH_CHECK_MAX_TOKENS_REASONING is not None:return int(BACKGROUND_HEALTH_CHECK_MAX_TOKENS_REASONING)if BACKGROUND_HEALTH_CHECK_MAX_TOKENS is not None:diff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.pyindex 5c2b3dfe0ee..f29bbd2d9d5 100644--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py@@ -1570,9 +1570,9 @@ class _PROXY_MaxParallelRequestsHandler_v3(CustomLogger):user_api_key_project_id = standard_logging_metadata.get("user_api_key_project_id")- user_api_key_end_user_id = kwargs.get(- "user"- ) or standard_logging_metadata.get("user_api_key_end_user_id")+ user_api_key_end_user_id = kwargs.get("user") or standard_logging_metadata.get(+ "user_api_key_end_user_id"+ )model_group = get_model_group_from_litellm_kwargs(kwargs)# Get total tokens from responsediff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.pyindex 8474f026111..c6d37ace4fe 100644--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py@@ -2120,9 +2120,7 @@ async def delete_user(for m in all_target_memberships:if not m.organization_id:continue- target_org_ids_by_user.setdefault(m.user_id, set()).add(- m.organization_id- )+ target_org_ids_by_user.setdefault(m.user_id, set()).add(m.organization_id)# check that all teams passed existfor user_id in data.user_ids:@@ -2141,9 +2139,7 @@ async def delete_user(# Org-admin may only delete users whose entire org membership is# within their admin scope. A target with ANY org outside the# caller's scope (or no org at all) requires PROXY_ADMIN.- if not target_org_ids or not target_org_ids.issubset(- caller_admin_org_ids- ):+ if not target_org_ids or not target_org_ids.issubset(caller_admin_org_ids):raise HTTPException(status_code=403,detail={diff --git a/litellm/proxy/management_endpoints/organization_endpoints.py b/litellm/proxy/management_endpoints/organization_endpoints.pyindex a6a1af971e5..442fae2a4fa 100644--- a/litellm/proxy/management_endpoints/organization_endpoints.py+++ b/litellm/proxy/management_endpoints/organization_endpoints.py@@ -1078,10 +1078,7 @@ async def organization_member_update(LitellmUserRoles.PROXY_ADMIN.value,LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,):- if (- user_api_key_dict.user_role- != LitellmUserRoles.PROXY_ADMIN.value- ):+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN.value:raise HTTPException(status_code=403,detail={diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.pyindex 8e21b851857..e4886eb6d15 100644--- a/litellm/proxy/management_endpoints/team_endpoints.py+++ b/litellm/proxy/management_endpoints/team_endpoints.py@@ -1570,8 +1570,7 @@ async def update_team( # noqa: PLR0915current_org_id = getattr(existing_team_row, "organization_id", None)if (data.organization_id != current_org_id- and user_api_key_dict.user_role- != LitellmUserRoles.PROXY_ADMIN.value+ and user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN.value):# Is the caller org_admin of the destination org?caller_memberships = (diff --git a/litellm/router_strategy/adaptive_router/hooks.py b/litellm/router_strategy/adaptive_router/hooks.pyindex 880c262f5d8..9e346006ac1 100644--- a/litellm/router_strategy/adaptive_router/hooks.py+++ b/litellm/router_strategy/adaptive_router/hooks.py@@ -102,7 +102,9 @@ def _last_user_content(messages: Optional[List[Dict[str, Any]]]) -> Optional[strreturn None-def _recent_tool_results(messages: Optional[List[Dict[str, Any]]]) -> List[Dict[str, Any]]:+def _recent_tool_results(+ messages: Optional[List[Dict[str, Any]]]+) -> List[Dict[str, Any]]:"""Extract the current turn's tool result payloads from the request messages.Tool results are `role == "tool"` messages that sit at the tail of thediff --git a/litellm/types/integrations/prometheus.py b/litellm/types/integrations/prometheus.pyindex 338c5a79ce6..43a287f29bc 100644--- a/litellm/types/integrations/prometheus.py+++ b/litellm/types/integrations/prometheus.py@@ -784,7 +784,7 @@ class UserAPIKeyLabelValues:org_id: Optional[str] = Noneorg_alias: Optional[str] = None- #Added for test compatibility.+ # Added for test compatibility.def __init__(self, **kwargs: Any) -> None:"""Match former Pydantic behavior: unknown keys are ignored; ``api_key_hash`` maps to