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]

chore(lint): clear grandfathered over-limit lint drift and ratchet budgets down

mateo-berri6c76f5f9c6ba
diff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.json
index d3259f88dce..ab5c6dcceaf 100644
--- a/basedpyright-code-budget.json
+++ b/basedpyright-code-budget.json
@@ -1,6 +1,6 @@
{
"reportAny": {
- "limit": 29809
+ "limit": 29806
},
"reportArgumentType": {
"limit": 2645
@@ -21,10 +21,10 @@
"limit": 215
},
"reportDuplicateImport": {
- "limit": 24
+ "limit": 19
},
"reportExplicitAny": {
- "limit": 9473
+ "limit": 9469
},
"reportFunctionMemberAccess": {
"limit": 7
@@ -105,13 +105,13 @@
"limit": 113
},
"reportUnknownMemberType": {
- "limit": 40452
+ "limit": 40447
},
"reportUnknownParameterType": {
"limit": 20309
},
"reportUnknownVariableType": {
- "limit": 31978
+ "limit": 31880
},
"reportUnnecessaryCast": {
"limit": 124
@@ -126,7 +126,7 @@
"limit": 866
},
"reportUntypedBaseClass": {
- "limit": 165
+ "limit": 72
},
"reportUntypedFunctionDecorator": {
"limit": 33
@@ -138,9 +138,9 @@
"limit": 139
},
"reportUnusedImport": {
- "limit": 588
+ "limit": 556
},
"reportUnusedVariable": {
- "limit": 147
+ "limit": 146
}
}
diff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.py
index 37f111c2324..89c72acc06d 100644
--- a/litellm/_lazy_imports_registry.py
+++ b/litellm/_lazy_imports_registry.py
@@ -1461,32 +1461,30 @@ _UTILS_MODULE_IMPORT_MAP: Final = {
# Export all name tuples and import maps for use in _lazy_imports.py
__all__ = [
- # Name tuples
- "COST_CALCULATOR_NAMES",
- "LITELLM_LOGGING_NAMES",
- "UTILS_NAMES",
- "TOKEN_COUNTER_NAMES",
- "LLM_CLIENT_CACHE_NAMES",
"BEDROCK_TYPES_NAMES",
- "TYPES_UTILS_NAMES",
"CACHING_NAMES",
- "HTTP_HANDLER_NAMES",
+ "COST_CALCULATOR_NAMES",
"DOTPROMPT_NAMES",
+ "HTTP_HANDLER_NAMES",
+ "LITELLM_LOGGING_NAMES",
+ "LLM_CLIENT_CACHE_NAMES",
"LLM_CONFIG_NAMES",
- "TYPES_NAMES",
"LLM_PROVIDER_LOGIC_NAMES",
+ "TOKEN_COUNTER_NAMES",
+ "TYPES_NAMES",
+ "TYPES_UTILS_NAMES",
"UTILS_MODULE_NAMES",
- # Import maps
- "_UTILS_IMPORT_MAP",
- "_COST_CALCULATOR_IMPORT_MAP",
- "_TYPES_UTILS_IMPORT_MAP",
- "_TOKEN_COUNTER_IMPORT_MAP",
+ "UTILS_NAMES",
"_BEDROCK_TYPES_IMPORT_MAP",
"_CACHING_IMPORT_MAP",
- "_LITELLM_LOGGING_IMPORT_MAP",
+ "_COST_CALCULATOR_IMPORT_MAP",
"_DOTPROMPT_IMPORT_MAP",
- "_TYPES_IMPORT_MAP",
+ "_LITELLM_LOGGING_IMPORT_MAP",
"_LLM_CONFIGS_IMPORT_MAP",
"_LLM_PROVIDER_LOGIC_IMPORT_MAP",
+ "_TOKEN_COUNTER_IMPORT_MAP",
+ "_TYPES_IMPORT_MAP",
+ "_TYPES_UTILS_IMPORT_MAP",
+ "_UTILS_IMPORT_MAP",
"_UTILS_MODULE_IMPORT_MAP",
]
diff --git a/litellm/_service_logger.py b/litellm/_service_logger.py
index 06ae3f41c19..42a86763b6d 100644
--- a/litellm/_service_logger.py
+++ b/litellm/_service_logger.py
@@ -1,6 +1,6 @@
import asyncio
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
import litellm
from litellm._logging import verbose_logger
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
from litellm.proxy._types import UserAPIKeyAuth
- Span = Union[_Span, Any]
+ Span = _Span | Any
OTELClass = OpenTelemetry
else:
Span = Any
diff --git a/litellm/a2a_protocol/__init__.py b/litellm/a2a_protocol/__init__.py
index 85c03687e25..380eb9a0e3f 100644
--- a/litellm/a2a_protocol/__init__.py
+++ b/litellm/a2a_protocol/__init__.py
@@ -55,19 +55,15 @@ from litellm.a2a_protocol.main import (
from litellm.types.agents import LiteLLMSendMessageResponse
__all__ = [
- # Client
+ "A2AAgentCardError",
"A2AClient",
- # Functions
+ "A2AConnectionError",
+ "A2AError",
+ "A2ALocalhostURLError",
+ "LiteLLMSendMessageResponse",
+ "aget_agent_card",
"asend_message",
- "send_message",
"asend_message_streaming",
- "aget_agent_card",
"create_a2a_client",
- # Response types
- "LiteLLMSendMessageResponse",
- # Exceptions
- "A2AError",
- "A2AConnectionError",
- "A2AAgentCardError",
- "A2ALocalhostURLError",
+ "send_message",
]
diff --git a/litellm/assistants/utils.py b/litellm/assistants/utils.py
index 44ff2213d94..e41cff8419a 100644
--- a/litellm/assistants/utils.py
+++ b/litellm/assistants/utils.py
@@ -57,7 +57,7 @@ def get_optional_params_add_message(
optional_params = litellm.AzureOpenAIAssistantsAPIConfig().map_openai_params_create_message_params(
non_default_params=non_default_params, optional_params=optional_params
)
- for k in passed_params.keys():
+ for k in passed_params:
if k not in default_params:
optional_params[k] = passed_params[k]
return optional_params
@@ -128,7 +128,7 @@ def get_optional_params_image_gen(
if n is not None:
optional_params["sampleCount"] = int(n)
- for k in passed_params.keys():
+ for k in passed_params:
if k not in default_params:
optional_params[k] = passed_params[k]
return optional_params
diff --git a/litellm/caching/base_cache.py b/litellm/caching/base_cache.py
index 6fe0609445f..51c169ba796 100644
--- a/litellm/caching/base_cache.py
+++ b/litellm/caching/base_cache.py
@@ -9,12 +9,12 @@ Has 4 methods:
"""
from abc import ABC, abstractmethod
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/caching/disk_cache.py b/litellm/caching/disk_cache.py
index 8843499adda..50939ad51ca 100644
--- a/litellm/caching/disk_cache.py
+++ b/litellm/caching/disk_cache.py
@@ -1,12 +1,12 @@
import json
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from .base_cache import BaseCache
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/caching/dual_cache.py b/litellm/caching/dual_cache.py
index 3b181ca23ff..598c9e67faf 100644
--- a/litellm/caching/dual_cache.py
+++ b/litellm/caching/dual_cache.py
@@ -13,7 +13,7 @@ import time
import traceback
from concurrent.futures import ThreadPoolExecutor
from threading import Lock
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
if TYPE_CHECKING:
from litellm.types.caching import RedisPipelineIncrementOperation
@@ -29,7 +29,7 @@ from .redis_cache import RedisCache
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.py
index ac0d871305c..5fedfc5bcce 100644
--- a/litellm/caching/redis_cache.py
+++ b/litellm/caching/redis_cache.py
@@ -18,7 +18,7 @@ import time
from collections.abc import Awaitable, Callable, Sequence
from contextvars import ContextVar
from datetime import timedelta
-from typing import TYPE_CHECKING, Any, Final, TypeVar, Union, cast
+from typing import TYPE_CHECKING, Any, Final, TypeVar, cast
import litellm
from litellm._logging import print_verbose, verbose_logger
@@ -49,7 +49,7 @@ if TYPE_CHECKING:
cluster_pipeline = ClusterPipeline
async_redis_client = Redis
async_redis_cluster_client = RedisCluster
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
pipeline = Any
cluster_pipeline = Any
diff --git a/litellm/caching/redis_cluster_cache.py b/litellm/caching/redis_cluster_cache.py
index 23a34f21f12..b6dd8047fd4 100644
--- a/litellm/caching/redis_cluster_cache.py
+++ b/litellm/caching/redis_cluster_cache.py
@@ -5,7 +5,7 @@ Key differences:
- RedisClient NEEDs to be re-used across requests, adds 3000ms latency if it's re-created
"""
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from litellm.caching.redis_cache import RedisCache
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
pipeline = Pipeline
async_redis_client = Redis
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
pipeline = Any
async_redis_client = Any
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index 7be69eb966f..f31e228e456 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -367,7 +367,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
stream_options = normalize_responses_api_stream_options(value)
if stream_options is not None:
responses_api_request["stream_options"] = stream_options
- elif key in ResponsesAPIOptionalRequestParams.__annotations__.keys():
+ elif key in ResponsesAPIOptionalRequestParams.__annotations__:
responses_api_request[key] = value
elif key == "previous_response_id":
responses_api_request["previous_response_id"] = value
diff --git a/litellm/containers/__init__.py b/litellm/containers/__init__.py
index 48ab5de4181..fc8664cc026 100644
--- a/litellm/containers/__init__.py
+++ b/litellm/containers/__init__.py
@@ -23,22 +23,20 @@ from .main import (
)
__all__ = [
- # Core container operations
"acreate_container",
"adelete_container",
- "alist_containers",
- "aretrieve_container",
- "create_container",
- "delete_container",
- "list_containers",
- "retrieve_container",
- # Container file operations (auto-generated from endpoints.json)
"adelete_container_file",
"alist_container_files",
+ "alist_containers",
+ "aretrieve_container",
"aretrieve_container_file",
"aretrieve_container_file_content",
+ "create_container",
+ "delete_container",
"delete_container_file",
"list_container_files",
+ "list_containers",
+ "retrieve_container",
"retrieve_container_file",
"retrieve_container_file_content",
]
diff --git a/litellm/integrations/arize/arize.py b/litellm/integrations/arize/arize.py
index bcab610835c..2e5b17185f2 100644
--- a/litellm/integrations/arize/arize.py
+++ b/litellm/integrations/arize/arize.py
@@ -6,7 +6,7 @@ this file has Arize ai specific helper functions
import os
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from litellm.integrations.arize import _utils
from litellm.integrations.arize._utils import ArizeOTELAttributes
@@ -21,7 +21,7 @@ if TYPE_CHECKING:
from litellm.types.integrations.arize import Protocol as _Protocol
Protocol = _Protocol
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Protocol = Any
Span = Any
diff --git a/litellm/integrations/arize/arize_phoenix.py b/litellm/integrations/arize/arize_phoenix.py
index baee5be6e5c..e13fc0184a4 100644
--- a/litellm/integrations/arize/arize_phoenix.py
+++ b/litellm/integrations/arize/arize_phoenix.py
@@ -1,7 +1,7 @@
import os
import threading
from collections import OrderedDict
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from litellm._logging import verbose_logger
from litellm.integrations.arize import _utils
@@ -22,7 +22,7 @@ if TYPE_CHECKING:
Protocol = _Protocol
OpenTelemetryConfig = _OpenTelemetryConfig
- Span = Union[_Span, Any]
+ Span = _Span | Any
OpenTelemetry = _OpenTelemetry
LITELLM_TRACER_NAME: str
else:
diff --git a/litellm/integrations/custom_logger.py b/litellm/integrations/custom_logger.py
index 0627a32266b..a0c78674ac8 100644
--- a/litellm/integrations/custom_logger.py
+++ b/litellm/integrations/custom_logger.py
@@ -3,7 +3,7 @@
import re
import traceback
from collections.abc import AsyncGenerator
-from typing import TYPE_CHECKING, Any, Final, Optional, Union
+from typing import TYPE_CHECKING, Any, Final, Optional
from pydantic import BaseModel
@@ -39,7 +39,7 @@ if TYPE_CHECKING:
)
from litellm.types.router import PreRoutingHookResponse
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
LiteLLMLoggingObj = Any
diff --git a/litellm/integrations/dotprompt/prompt_manager.py b/litellm/integrations/dotprompt/prompt_manager.py
index ceaaa37607e..46750ed9799 100644
--- a/litellm/integrations/dotprompt/prompt_manager.py
+++ b/litellm/integrations/dotprompt/prompt_manager.py
@@ -31,7 +31,7 @@ class PromptTemplate:
self.output_format = self.metadata.get("output", {}).get("format")
self.output_schema = self.metadata.get("output", {}).get("schema", {})
self.optional_params = {}
- for key in self.metadata.keys():
+ for key in self.metadata:
if key not in restricted_keys:
self.optional_params[key] = self.metadata[key]
diff --git a/litellm/integrations/langfuse/langfuse_otel.py b/litellm/integrations/langfuse/langfuse_otel.py
index 9f317e65e47..7de42c00ede 100644
--- a/litellm/integrations/langfuse/langfuse_otel.py
+++ b/litellm/integrations/langfuse/langfuse_otel.py
@@ -2,7 +2,7 @@ import base64
import json
import os
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final, Optional, Union
+from typing import TYPE_CHECKING, Any, Final, Optional
from litellm._logging import verbose_logger
from litellm.integrations.arize import _utils
@@ -18,7 +18,7 @@ from litellm.types.utils import StandardCallbackDynamicParams
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/integrations/langfuse/langfuse_prompt_management.py b/litellm/integrations/langfuse/langfuse_prompt_management.py
index 85e2a19565e..d8d03b73d14 100644
--- a/litellm/integrations/langfuse/langfuse_prompt_management.py
+++ b/litellm/integrations/langfuse/langfuse_prompt_management.py
@@ -4,7 +4,7 @@ Call Hook for LiteLLM Proxy which allows Langfuse prompt management.
import os
from functools import lru_cache
-from typing import TYPE_CHECKING, Any, Final, Literal, TypeAlias, Union, cast
+from typing import TYPE_CHECKING, Any, Final, Literal, TypeAlias, cast
from packaging.version import Version
@@ -30,7 +30,7 @@ if TYPE_CHECKING:
LangfuseClass: TypeAlias = Langfuse
- PROMPT_CLIENT = Union[TextPromptClient, ChatPromptClient]
+ PROMPT_CLIENT = TextPromptClient | ChatPromptClient
else:
PROMPT_CLIENT = Any
LangfuseClass = Any
diff --git a/litellm/integrations/langtrace.py b/litellm/integrations/langtrace.py
index 7ec1c4551e5..0b4e1393ee6 100644
--- a/litellm/integrations/langtrace.py
+++ b/litellm/integrations/langtrace.py
@@ -1,12 +1,12 @@
import json
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from litellm.proxy._types import SpanAttributes
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/integrations/levo/levo.py b/litellm/integrations/levo/levo.py
index 12eac44b838..4d2b4edf3cd 100644
--- a/litellm/integrations/levo/levo.py
+++ b/litellm/integrations/levo/levo.py
@@ -1,5 +1,5 @@
import os
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from litellm.integrations.opentelemetry import OpenTelemetry
@@ -13,7 +13,7 @@ if TYPE_CHECKING:
Protocol = _Protocol
OpenTelemetryConfig = _OpenTelemetryConfig
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Protocol = Any
OpenTelemetryConfig = Any
diff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.py
index e21a362ffcb..39dbf8ed487 100644
--- a/litellm/integrations/opentelemetry.py
+++ b/litellm/integrations/opentelemetry.py
@@ -1,7 +1,7 @@
import os
from dataclasses import dataclass, field
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final, Union, cast
+from typing import TYPE_CHECKING, Any, Final, cast
import litellm
from litellm._logging import verbose_logger
@@ -47,12 +47,12 @@ if TYPE_CHECKING:
)
from litellm.proxy.proxy_server import UserAPIKeyAuth as _UserAPIKeyAuth
- Span = Union[_Span, Any]
- Tracer = Union[_Tracer, Any]
- Context = Union[_Context, Any]
- SpanExporter = Union[_SpanExporter, Any]
- UserAPIKeyAuth = Union[_UserAPIKeyAuth, Any]
- ManagementEndpointLoggingPayload = Union[_ManagementEndpointLoggingPayload, Any]
+ Span = _Span | Any
+ Tracer = _Tracer | Any
+ Context = _Context | Any
+ SpanExporter = _SpanExporter | Any
+ UserAPIKeyAuth = _UserAPIKeyAuth | Any
+ ManagementEndpointLoggingPayload = _ManagementEndpointLoggingPayload | Any
else:
Span = Any
Tracer = Any
@@ -186,16 +186,7 @@ def _normalize_team_metadata_keys(value: Any) -> list[str]:
_FREEZE_MAX_DEPTH: Final = 16
-HashableScope = Union[
- str,
- int,
- float,
- bool,
- bytes,
- None,
- tuple["HashableScope", ...],
- frozenset["HashableScope"],
-]
+HashableScope = str | int | float | bool | bytes | None | tuple["HashableScope", ...] | frozenset["HashableScope"]
def _freeze_for_dedupe(value: object, _depth: int = 0) -> HashableScope:
diff --git a/litellm/integrations/opentelemetry_utils/gen_ai_semconv.py b/litellm/integrations/opentelemetry_utils/gen_ai_semconv.py
index a4ad886aec7..0e58cf67795 100644
--- a/litellm/integrations/opentelemetry_utils/gen_ai_semconv.py
+++ b/litellm/integrations/opentelemetry_utils/gen_ai_semconv.py
@@ -31,7 +31,7 @@ Events:
from datetime import datetime
from enum import Enum
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
@@ -40,7 +40,7 @@ if TYPE_CHECKING:
from litellm.integrations.opentelemetry import OpenTelemetryConfig
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/integrations/opik/opik_payload_builder/types.py b/litellm/integrations/opik/opik_payload_builder/types.py
index ca14c406bac..546ce55f840 100644
--- a/litellm/integrations/opik/opik_payload_builder/types.py
+++ b/litellm/integrations/opik/opik_payload_builder/types.py
@@ -1,7 +1,7 @@
"""Type definitions for Opik payload building."""
from dataclasses import dataclass
-from typing import Any, Final, Literal, Union
+from typing import Any, Final, Literal
@dataclass
@@ -42,5 +42,5 @@ class SpanPayload:
total_cost: float | None = None
-PayloadItem = Union[TracePayload, SpanPayload]
+PayloadItem = TracePayload | SpanPayload
TraceSpanPayloadTuple: Final = tuple[TracePayload | None, SpanPayload]
diff --git a/litellm/integrations/otel/__init__.py b/litellm/integrations/otel/__init__.py
index 8e11f55f46f..94442e96adb 100644
--- a/litellm/integrations/otel/__init__.py
+++ b/litellm/integrations/otel/__init__.py
@@ -72,53 +72,49 @@ from litellm.integrations.otel.model.spans import (
)
__all__ = [
- # config
- "OTEL_V2_ENV",
- "OpenTelemetryV2Config",
- "is_otel_v2_enabled",
- # semconv
"BAGGAGE_PROMOTED_KEYS",
"DB",
"DEFAULT_BAGGAGE_METADATA_KEYS",
+ "HTTP",
+ "MCP",
+ "OTEL_V2_ENV",
+ "SPAN_REGISTRY",
"Client",
"Error",
"GenAI",
"GenAIOperation",
"GenAIProvider",
- "HTTP",
+ "GuardrailSpanData",
"JsonRpc",
+ "LLMCallSpanData",
+ "LLMRequestParams",
+ "LLMUsage",
"LiteLLM",
"LiteLLMError",
- "MCP",
+ "LiteLLMSpanKind",
+ "MCPListToolsSpanData",
"MCPMethod",
+ "MCPToolCallSpanData",
"Metric",
"Network",
"NetworkTransport",
- "Server",
- "resolve_operation",
- "resolve_provider",
- # spans
- "SPAN_REGISTRY",
- "LiteLLMSpanKind",
- "SpanRole",
- "SpanSpec",
- "db_system",
- "span_role_for_service",
- "validate_registry",
- # payloads
- "GuardrailSpanData",
- "LLMCallSpanData",
- "LLMRequestParams",
- "LLMUsage",
- "MCPListToolsSpanData",
- "MCPToolCallSpanData",
+ "OpenTelemetryV2Config",
"ProxyRequestSpanData",
"RequestContext",
"RequestIdentity",
+ "Server",
"ServerInfo",
"ServiceSpanData",
"SpanError",
+ "SpanRole",
+ "SpanSpec",
+ "db_system",
"is_mcp_list_tools",
"is_mcp_tool_call",
+ "is_otel_v2_enabled",
"promoted_baggage",
+ "resolve_operation",
+ "resolve_provider",
+ "span_role_for_service",
+ "validate_registry",
]
diff --git a/litellm/interactions/__init__.py b/litellm/interactions/__init__.py
index ed01462cba6..6129cd87153 100644
--- a/litellm/interactions/__init__.py
+++ b/litellm/interactions/__init__.py
@@ -66,18 +66,13 @@ from litellm.interactions.main import (
)
__all__ = [
- # Create
- "create",
+ "acancel",
"acreate",
- # Get
- "get",
- "aget",
- # Delete
- "delete",
"adelete",
- # Cancel
- "cancel",
- "acancel",
- # Sub-modules
"agents",
+ "aget",
+ "cancel",
+ "create",
+ "delete",
+ "get",
]
diff --git a/litellm/litellm_core_utils/core_helpers.py b/litellm/litellm_core_utils/core_helpers.py
index cb9d36f2dfd..40592595a33 100644
--- a/litellm/litellm_core_utils/core_helpers.py
+++ b/litellm/litellm_core_utils/core_helpers.py
@@ -2,7 +2,7 @@
## Helper utilities
import copy
from collections.abc import Iterable
-from typing import TYPE_CHECKING, Any, Final, Literal, Union
+from typing import TYPE_CHECKING, Any, Final, Literal
import httpx
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
from litellm.types.utils import ModelResponseStream
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/litellm_core_utils/fallback_generalizations.py b/litellm/litellm_core_utils/fallback_generalizations.py
index 3f383426691..7739fc82c77 100644
--- a/litellm/litellm_core_utils/fallback_generalizations.py
+++ b/litellm/litellm_core_utils/fallback_generalizations.py
@@ -48,7 +48,7 @@ O(number of rules); callers must only invoke them on a cache miss.
import re
from dataclasses import dataclass
-from typing import Final, Union
+from typing import Final
from litellm._logging import verbose_logger
@@ -100,7 +100,7 @@ class _CapabilityRule:
model_info: dict
-_CompiledRule = Union[_RoutingRule, _CapabilityRule]
+_CompiledRule = _RoutingRule | _CapabilityRule
def _compile_rule(rule: object) -> tuple[_CompiledRule, ...]:
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index f824e9b2c64..6ba06919e00 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -4827,7 +4827,7 @@ class StandardLoggingPayloadSetup:
# Populate well-known typed fields with int/str coercion where needed
typed_keys: Final[dict] = {}
- for key in StandardLoggingAdditionalHeaders.__annotations__.keys():
+ for key in StandardLoggingAdditionalHeaders.__annotations__:
_key = key.lower().replace("_", "-")
typed_keys[_key] = key
if _key in additiona_headers:
@@ -4859,7 +4859,7 @@ class StandardLoggingPayloadSetup:
usage_object=None,
)
if hidden_params is not None:
- for key in StandardLoggingHiddenParams.__annotations__.keys():
+ for key in StandardLoggingHiddenParams.__annotations__:
if key in hidden_params:
if key == "additional_headers":
clean_hidden_params["additional_headers"] = StandardLoggingPayloadSetup.get_additional_headers(
@@ -5501,7 +5501,7 @@ def get_standard_logging_metadata(
)
if isinstance(metadata, dict):
# Update the clean_metadata with values from input metadata that match StandardLoggingMetadata fields
- for key in StandardLoggingMetadata.__annotations__.keys():
+ for key in StandardLoggingMetadata.__annotations__:
if key in metadata:
clean_metadata[key] = metadata[key]
diff --git a/litellm/litellm_core_utils/logging_utils.py b/litellm/litellm_core_utils/logging_utils.py
index 0dde3cc3c03..a17415f3ab8 100644
--- a/litellm/litellm_core_utils/logging_utils.py
+++ b/litellm/litellm_core_utils/logging_utils.py
@@ -4,7 +4,7 @@ import inspect
import re
import time
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from litellm._logging import verbose_logger
from litellm.constants import MAX_BASE64_LENGTH_FOR_LOGGING
@@ -23,7 +23,7 @@ if TYPE_CHECKING:
)
LiteLLMModelResponse = _ModelResponse
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
LiteLLMModelResponse = Any
LiteLLMLoggingObject = Any
diff --git a/litellm/litellm_core_utils/model_response_utils.py b/litellm/litellm_core_utils/model_response_utils.py
index 00a8c7ff09e..ea4be1c856f 100644
--- a/litellm/litellm_core_utils/model_response_utils.py
+++ b/litellm/litellm_core_utils/model_response_utils.py
@@ -47,7 +47,7 @@ def is_model_response_stream_empty(model_response: ModelResponseStream) -> bool:
# Check for any non-base fields that are set
# Access model_fields on the class, not the instance, to avoid Pydantic 2.11+ deprecation warnings
- for model_response_field in type(model_response).model_fields.keys():
+ for model_response_field in type(model_response).model_fields:
# Skip base fields that are always set
if model_response_field in BASE_FIELDS:
continue
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py
index be5694b7554..68465d06b15 100644
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@ -8,7 +8,7 @@ import time
import traceback
from collections.abc import AsyncIterator, Callable, Iterator
from dataclasses import dataclass
-from typing import Any, Final, NoReturn, TypeVar, Union, cast
+from typing import Any, Final, NoReturn, TypeVar, cast
import anyio
import httpx
@@ -99,7 +99,7 @@ class _ProviderChunkEarlyReturn:
value: Any
-_ProviderChunkResult = Union[_ProviderChunkParsed, _ProviderChunkEarlyReturn]
+_ProviderChunkResult = _ProviderChunkParsed | _ProviderChunkEarlyReturn
class CustomStreamWrapper:
@@ -256,9 +256,7 @@ class CustomStreamWrapper:
chunk = chunk.strip()
self.complete_response = self.complete_response.strip()
- if chunk.startswith(self.complete_response):
- # Remove last_sent_chunk only if it appears at the start of the new chunk
- chunk = chunk[len(self.complete_response) :]
+ chunk = chunk.removeprefix(self.complete_response)
self.complete_response += chunk
return chunk
diff --git a/litellm/llms/base_llm/managed_resources/base_managed_resource.py b/litellm/llms/base_llm/managed_resources/base_managed_resource.py
index d02d6c83e03..2a59eddf88a 100644
--- a/litellm/llms/base_llm/managed_resources/base_managed_resource.py
+++ b/litellm/llms/base_llm/managed_resources/base_managed_resource.py
@@ -5,7 +5,7 @@
import base64
import json
from abc import ABC, abstractmethod
-from typing import TYPE_CHECKING, Any, Final, Generic, TypeVar, Union, cast
+from typing import TYPE_CHECKING, Any, Final, Generic, TypeVar, cast
from litellm import verbose_logger
from litellm.llms.base_llm.managed_resources.isolation import (
@@ -23,7 +23,7 @@ if TYPE_CHECKING:
from litellm.proxy.utils import PrismaClient as _PrismaClient
from litellm.router import Router as _Router
- Span = Union[_Span, Any]
+ Span = _Span | Any
InternalUsageCache = _InternalUsageCache
PrismaClient = _PrismaClient
Router = _Router
diff --git a/litellm/llms/bedrock/embed/cohere_transformation.py b/litellm/llms/bedrock/embed/cohere_transformation.py
index e1239ad6a4e..d1c9ceb99d1 100644
--- a/litellm/llms/bedrock/embed/cohere_transformation.py
+++ b/litellm/llms/bedrock/embed/cohere_transformation.py
@@ -34,7 +34,7 @@ class BedrockCohereEmbeddingConfig:
new_transformed_request: Final = CohereEmbeddingRequest(
input_type=transformed_request["input_type"],
)
- for k in CohereEmbeddingRequest.__annotations__.keys():
+ for k in CohereEmbeddingRequest.__annotations__:
if k in transformed_request:
new_transformed_request[k] = transformed_request[k]
diff --git a/litellm/llms/bedrock/image_generation/image_handler.py b/litellm/llms/bedrock/image_generation/image_handler.py
index a30e287a119..6fac14a0dc3 100644
--- a/litellm/llms/bedrock/image_generation/image_handler.py
+++ b/litellm/llms/bedrock/image_generation/image_handler.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import json
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
import httpx
from pydantic import BaseModel
@@ -49,12 +49,12 @@ class BedrockImagePreparedRequest(BaseModel):
data: dict
-BedrockImageConfigClass = Union[
- type[AmazonTitanImageGenerationConfig],
- type[AmazonNovaCanvasConfig],
- type[AmazonStability3Config],
- type[AmazonStabilityConfig],
-]
+BedrockImageConfigClass = (
+ type[AmazonTitanImageGenerationConfig]
+ | type[AmazonNovaCanvasConfig]
+ | type[AmazonStability3Config]
+ | type[AmazonStabilityConfig]
+)
class BedrockImageGeneration(BaseAWSLLM):
diff --git a/litellm/llms/bedrock/vector_stores/transformation.py b/litellm/llms/bedrock/vector_stores/transformation.py
index c8d0e51a651..2d72db0cdba 100644
--- a/litellm/llms/bedrock/vector_stores/transformation.py
+++ b/litellm/llms/bedrock/vector_stores/transformation.py
@@ -160,10 +160,10 @@ class BedrockVectorStoreConfig(BaseVectorStoreConfig, BaseAWSLLM):
aws_filters: dict | None = None
if isinstance(value, dict):
- if "operator" in value.keys():
+ if "operator" in value:
# Single operator - map directly (no wrapping needed)
aws_filters = self._map_operator_filter(value)
- elif "and" in value.keys() or "or" in value.keys():
+ elif "and" in value or "or" in value:
aws_filters = self._map_and_or_filters(value)
else:
# Assume it's already in AWS KB format
diff --git a/litellm/llms/openai/transcriptions/whisper_transformation.py b/litellm/llms/openai/transcriptions/whisper_transformation.py
index 5e4bb19cbb3..8fb9dd1318e 100644
--- a/litellm/llms/openai/transcriptions/whisper_transformation.py
+++ b/litellm/llms/openai/transcriptions/whisper_transformation.py
@@ -132,7 +132,7 @@ class OpenAIWhisperAudioTranscriptionConfig(BaseAudioTranscriptionConfig):
raise
return TranscriptionResponse(text=raw_response.text)
- if any(key in raw_response_json for key in TranscriptionResponse.model_fields.keys()):
+ if any(key in raw_response_json for key in TranscriptionResponse.model_fields):
return TranscriptionResponse(**raw_response_json)
else:
raise ValueError(
diff --git a/litellm/llms/sap/chat/models.py b/litellm/llms/sap/chat/models.py
index 4d7ae62767f..5f65c7f715d 100644
--- a/litellm/llms/sap/chat/models.py
+++ b/litellm/llms/sap/chat/models.py
@@ -1,6 +1,6 @@
import warnings
from enum import Enum
-from typing import Final, Literal, Union
+from typing import Final, Literal
from pydantic import BaseModel, Field, field_validator, model_validator
@@ -115,7 +115,7 @@ class SAPToolChatMessage(BaseModel):
_content_validator = field_validator("content", mode="before")(validate_different_content)
-ChatMessage = Union[SAPMessage, SAPUserMessage, SAPAssistantMessage, SAPToolChatMessage]
+ChatMessage = SAPMessage | SAPUserMessage | SAPAssistantMessage | SAPToolChatMessage
class ResponseFormat(BaseModel):
diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
index 5971884201a..ff51f1a013e 100644
--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py
@@ -11,8 +11,6 @@ from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Union, cast
import httpx
import litellm
-import litellm.litellm_core_utils
-import litellm.litellm_core_utils.litellm_logging
from litellm import verbose_logger
from litellm._uuid import uuid
from litellm.constants import (
@@ -2429,7 +2427,7 @@ class VertexGeminiConfig(VertexAIBaseConfig, BaseConfig):
_candidates: Final = completion_response.get("candidates")
if _candidates and len(_candidates) > 0:
content_policy_violations: Final = VertexGeminiConfig().get_flagged_finish_reasons()
- if "finishReason" in _candidates[0] and _candidates[0]["finishReason"] in content_policy_violations.keys():
+ if "finishReason" in _candidates[0] and _candidates[0]["finishReason"] in content_policy_violations:
return self._handle_content_policy_violation(
model_response=model_response,
completion_response=completion_response,
diff --git a/litellm/main.py b/litellm/main.py
index f906c78f9ae..edef60e14ee 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -322,7 +322,7 @@ oci_transformation: Final = OCIChatConfig()
ovhcloud_transformation: Final = OVHCloudChatConfig()
lemonade_transformation: Final = LemonadeChatConfig()
-MOCK_RESPONSE_TYPE = Union[str, Exception, dict, ModelResponse, ModelResponseStream]
+MOCK_RESPONSE_TYPE = str | Exception | dict | ModelResponse | ModelResponseStream
####### COMPLETION ENDPOINTS ################
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index 7baed21078d..c8ff6e262d2 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -3375,10 +3375,10 @@ class MCPServerManager:
static_headers: Final = server.static_headers or {}
has_static_authorization: Final = any(
- isinstance(k, str) and k.lower() == "authorization" for k in static_headers.keys()
+ isinstance(k, str) and k.lower() == "authorization" for k in static_headers
)
has_extra_authorization: Final = bool(extra_headers) and any(
- isinstance(k, str) and k.lower() == "authorization" for k in (extra_headers or {}).keys()
+ isinstance(k, str) and k.lower() == "authorization" for k in (extra_headers or {})
)
if (
@@ -4419,7 +4419,7 @@ class MCPServerManager:
allowed_params_list: Final = allowed_params[matched]
# Filter arguments to only include allowed parameters
- disallowed_params: Final = [param for param in arguments.keys() if param not in allowed_params_list]
+ disallowed_params: Final = [param for param in arguments if param not in allowed_params_list]
if disallowed_params:
raise HTTPException(
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index ef7bfd4b4f6..1c6ad84ddb4 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -1613,7 +1613,7 @@ if MCP_AVAILABLE:
``mcp_server_auth_headers``). Either form skips the pre-emptive 401.
"""
if oauth2_headers:
- for k in oauth2_headers.keys():
+ for k in oauth2_headers:
if k.lower() == "authorization":
return True
return _client_has_per_server_auth_header(server, mcp_server_auth_headers)
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 75ce20b5b11..4e5782c862a 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -3,7 +3,7 @@ import json
import os
from collections.abc import Callable
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final, Literal, Union
+from typing import TYPE_CHECKING, Any, Final, Literal
import httpx
from pydantic import (
@@ -67,7 +67,7 @@ from .types_utils.utils import get_instance_fn, validate_custom_validate_return_
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
@@ -4010,7 +4010,7 @@ class JWTKeyItem(TypedDict, total=False):
kid: str
-JWKKeyValue = Union[list[JWTKeyItem], JWTKeyItem]
+JWKKeyValue = list[JWTKeyItem] | JWTKeyItem
class JWKUrlResponse(TypedDict, total=False):
@@ -4053,15 +4053,15 @@ class UserManagementEndpointParamDocStringEnums(str, enum.Enum):
duration_doc_str = """Optional[str] - Duration for the key auto-created on `/user/new`. Default is None."""
-PassThroughEndpointLoggingResultValues = Union[
- ModelResponse,
- TextCompletionResponse,
- ImageResponse,
- EmbeddingResponse,
- VideoObject,
- StandardPassThroughResponseObject,
- ResponsesAPIResponse,
-]
+PassThroughEndpointLoggingResultValues = (
+ ModelResponse
+ | TextCompletionResponse
+ | ImageResponse
+ | EmbeddingResponse
+ | VideoObject
+ | StandardPassThroughResponseObject
+ | ResponsesAPIResponse
+)
class PassThroughEndpointLoggingTypedDict(TypedDict):
@@ -4162,7 +4162,7 @@ class ClientSideFallbackModel(TypedDict, total=False):
messages: list[AllMessageValues]
-ALL_FALLBACK_MODEL_VALUES = Union[str, ClientSideFallbackModel]
+ALL_FALLBACK_MODEL_VALUES = str | ClientSideFallbackModel
RBAC_ROLES = Literal[
diff --git a/litellm/proxy/a2a/version_convert.py b/litellm/proxy/a2a/version_convert.py
index d0a0f2a27e4..35587ee274c 100644
--- a/litellm/proxy/a2a/version_convert.py
+++ b/litellm/proxy/a2a/version_convert.py
@@ -26,7 +26,7 @@ The two wire shapes:
from collections.abc import Callable
from types import ModuleType
-from typing import Final, Literal, Union
+from typing import Final, Literal
from pydantic import BaseModel
@@ -34,7 +34,7 @@ from litellm._logging import verbose_proxy_logger
from litellm.proxy.a2a.agent_card import normalize_protocol_version
A2AVersion = Literal["0.3", "1.0"]
-RequestId = Union[str, int, None]
+RequestId = str | int | None
JsonDict = dict[str, object]
_V1_SEND_ENVELOPE_KEYS: Final = frozenset({"message", "task"})
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index 5ef4eb471ad..1a1a1fdb90d 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -13,7 +13,7 @@ import asyncio
import math
import re
import time
-from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Union, cast
+from typing import TYPE_CHECKING, Any, Final, Literal, Optional, cast
from fastapi import HTTPException, Request, status
from pydantic import BaseModel
@@ -109,7 +109,7 @@ from .auth_utils import get_model_from_request, get_request_route_template
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/proxy/auth/auth_exception_handler.py b/litellm/proxy/auth/auth_exception_handler.py
index 6f60c8f8e30..603e72463bc 100644
--- a/litellm/proxy/auth/auth_exception_handler.py
+++ b/litellm/proxy/auth/auth_exception_handler.py
@@ -2,7 +2,7 @@
Handles Authentication Errors
"""
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from fastapi import HTTPException, Request, status
@@ -28,7 +28,7 @@ DB_UNAVAILABLE_FALLBACK_USER_ID: Final = "__db_unavailable_fallback__"
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/proxy/auth/ip_address_utils.py b/litellm/proxy/auth/ip_address_utils.py
index 5a27905dfb9..558ea54495f 100644
--- a/litellm/proxy/auth/ip_address_utils.py
+++ b/litellm/proxy/auth/ip_address_utils.py
@@ -7,7 +7,7 @@ External callers (public IPs) only see servers with available_on_public_internet
import ipaddress
from dataclasses import dataclass
-from typing import Any, Final, Union
+from typing import Any, Final
from fastapi import Request
from pydantic import TypeAdapter, ValidationError
@@ -45,7 +45,7 @@ class _HopCount:
value: int
-_HopCountSetting = Union[_HopCountUnset, _HopCountInvalid, _HopCount]
+_HopCountSetting = _HopCountUnset | _HopCountInvalid | _HopCount
class IPAddressUtils:
diff --git a/litellm/proxy/auth/network.py b/litellm/proxy/auth/network.py
index f3d255bcf2b..32ad18d4deb 100644
--- a/litellm/proxy/auth/network.py
+++ b/litellm/proxy/auth/network.py
@@ -1,14 +1,14 @@
from __future__ import annotations
import ipaddress
-from typing import Any, Final, Union
+from typing import Any, Final
from fastapi import Request
from pydantic import BaseModel, Field
from litellm._logging import verbose_proxy_logger
-TrustedProxyNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
+TrustedProxyNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
class NetworkContext(BaseModel):
diff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.py
index f6a46f25db8..dd84b1c1a8d 100644
--- a/litellm/proxy/batches_endpoints/endpoints.py
+++ b/litellm/proxy/batches_endpoints/endpoints.py
@@ -177,7 +177,7 @@ async def create_batch(
}
input_file_id: Final = _create_batch_data.get("input_file_id", None)
- unified_file_id: Union[str, Literal[False]] = False
+ unified_file_id: str | Literal[False] = False
model_from_file_id = None
if input_file_id:
diff --git a/litellm/proxy/client/cli/commands/autoroute/config.py b/litellm/proxy/client/cli/commands/autoroute/config.py
index f3e9a52d478..9dfc4ad079b 100644
--- a/litellm/proxy/client/cli/commands/autoroute/config.py
+++ b/litellm/proxy/client/cli/commands/autoroute/config.py
@@ -1,4 +1,4 @@
-from typing import Final, Literal, Union
+from typing import Final, Literal
from pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter
@@ -56,7 +56,7 @@ class LLMClassifier(BaseModel):
timeout_ms: int = 3000
-ClassifierChoice = Union[HeuristicClassifier, LLMClassifier]
+ClassifierChoice = HeuristicClassifier | LLMClassifier
class NoSemanticMatching(BaseModel):
@@ -88,7 +88,7 @@ class SemanticMatching(BaseModel):
keyword_tier_rules: tuple[KeywordTierRule, ...] = DEFAULT_KEYWORD_TIER_RULES
-SemanticMatchingChoice = Union[NoSemanticMatching, SemanticMatching]
+SemanticMatchingChoice = NoSemanticMatching | SemanticMatching
class AutorouteConfig(BaseModel):
diff --git a/litellm/proxy/db/db_spend_update_writer.py b/litellm/proxy/db/db_spend_update_writer.py
index d893471e66e..acc8c71b84b 100644
--- a/litellm/proxy/db/db_spend_update_writer.py
+++ b/litellm/proxy/db/db_spend_update_writer.py
@@ -1230,7 +1230,7 @@ class DBSpendUpdateWriter:
if team_member_list_transactions is not None and len(team_member_list_transactions.keys()) > 0:
# Track which team memberships will be updated for cache invalidation
team_memberships_to_invalidate: Final[list[tuple[str, str]]] = []
- for key in team_member_list_transactions.keys():
+ for key in team_member_list_transactions:
# key is "team_id::<value>::user_id::<value>"
team_id = key.split("::")[1]
user_id = key.split("::")[3]
diff --git a/litellm/proxy/enterprise_billing/billing_metrics.py b/litellm/proxy/enterprise_billing/billing_metrics.py
index 31ab791334d..166ece28b83 100644
--- a/litellm/proxy/enterprise_billing/billing_metrics.py
+++ b/litellm/proxy/enterprise_billing/billing_metrics.py
@@ -16,7 +16,7 @@ payload; the secret license key is never sent as an attribute or header.
import os
import tempfile
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Final, Optional, Union
+from typing import TYPE_CHECKING, Final, Optional
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.metrics import Counter
@@ -53,7 +53,7 @@ _CA_CERT_FILENAME: Final = "ca.crt"
METRIC_NAME: Final = "litellm.enterprise.billable_requests"
METER_NAME: Final = "litellm.enterprise.billing"
-AttributeValue = Union[str, int]
+AttributeValue = str | int
@dataclass(frozen=True, slots=True)
diff --git a/litellm/proxy/fine_tuning_endpoints/endpoints.py b/litellm/proxy/fine_tuning_endpoints/endpoints.py
index 8a1e16f5aba..f8ffb77edb8 100644
--- a/litellm/proxy/fine_tuning_endpoints/endpoints.py
+++ b/litellm/proxy/fine_tuning_endpoints/endpoints.py
@@ -132,7 +132,7 @@ async def create_fine_tuning_job(
)
## CHECK IF MANAGED FILE ID
- unified_file_id: Union[str, Literal[False]] = False
+ unified_file_id: str | Literal[False] = False
training_file: Final = fine_tuning_request.training_file
response: LiteLLMFineTuningJob | None = None
if training_file:
@@ -269,7 +269,7 @@ async def retrieve_fine_tuning_job(
custom_llm_provider = request_body.get("custom_llm_provider", None) or custom_llm_provider
## CHECK IF MANAGED FILE ID
- unified_finetuning_job_id: Union[str, Literal[False]] = False
+ unified_finetuning_job_id: str | Literal[False] = False
response: LiteLLMFineTuningJob | None = None
if fine_tuning_job_id:
unified_finetuning_job_id = _is_base64_encoded_unified_file_id(fine_tuning_job_id)
@@ -536,7 +536,7 @@ async def cancel_fine_tuning_job(
custom_llm_provider: Final = request_body.get("custom_llm_provider", None)
## CHECK IF MANAGED FILE ID
- unified_finetuning_job_id: Union[str, Literal[False]] = False
+ unified_finetuning_job_id: str | Literal[False] = False
response: LiteLLMFineTuningJob | None = None
if fine_tuning_job_id:
unified_finetuning_job_id = _is_base64_encoded_unified_file_id(fine_tuning_job_id)
diff --git a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py
index 5105f7ffe9a..16768a4b08f 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/generic_guardrail_api.py
@@ -265,7 +265,7 @@ class GenericGuardrailAPI(CustomGuardrail):
# Dynamically iterate through GenericGuardrailAPIMetadata fields
# and extract matching fields from the source metadata
# Fields in metadata are already prefixed with 'user_api_key_'
- for field_name in GenericGuardrailAPIMetadata.__annotations__.keys():
+ for field_name in GenericGuardrailAPIMetadata.__annotations__:
value = metadata_dict.get(field_name)
if value is not None:
result_metadata[field_name] = value
diff --git a/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py b/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
index 82125247c56..d187b5b12e9 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/model_armor/model_armor.py
@@ -1,5 +1,5 @@
from collections.abc import AsyncGenerator, Mapping, Sequence
-from typing import TYPE_CHECKING, Any, Final, Literal, Union
+from typing import TYPE_CHECKING, Any, Final, Literal
import httpx
from fastapi import HTTPException
@@ -57,7 +57,7 @@ class ModelArmorAPIError(Exception):
_SCANNED_CONTENT_KEYS: Final = frozenset({"text", "sanitizedText", "findings", "maliciousUriMatchedItems"})
-RedactablePayload = Union[dict, list, str, int, float, bool, None]
+RedactablePayload = dict | list | str | int | float | bool | None
def _redact_scanned_content(payload: RedactablePayload, depth: int = 0) -> RedactablePayload:
diff --git a/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py b/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py
index fac8c98d349..385e7d61dee 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py
@@ -16,7 +16,6 @@ from typing import (
Any,
Final,
Literal,
- Union,
)
from urllib.parse import urljoin
@@ -54,7 +53,7 @@ SENSITIVE_DATA_DETECTOR_KEYS: Final[list[str]] = ["sensitiveData", "dataDetector
# Type aliases
MessageRole = Literal["user", "assistant"]
-LLMResponse = Union[Any, ModelResponse, EmbeddingResponse, ImageResponse]
+LLMResponse = Any | ModelResponse | EmbeddingResponse | ImageResponse
_LEGACY_NOMA_DEPRECATION_WARNED = False
if TYPE_CHECKING:
diff --git a/litellm/proxy/guardrails/usage_endpoints.py b/litellm/proxy/guardrails/usage_endpoints.py
index 33fae1ae57f..029a26e84f8 100644
--- a/litellm/proxy/guardrails/usage_endpoints.py
+++ b/litellm/proxy/guardrails/usage_endpoints.py
@@ -6,7 +6,7 @@ GET /guardrails/usage/overview, /guardrails/usage/detail/:id, /guardrails/usage/
import json
from collections.abc import Mapping, Sequence
from datetime import datetime, timedelta, timezone
-from typing import TYPE_CHECKING, Any, Final, Literal, Union, overload
+from typing import TYPE_CHECKING, Any, Final, Literal, overload
from fastapi import APIRouter, Depends, Query
from pydantic import BaseModel
@@ -31,8 +31,8 @@ if TYPE_CHECKING:
from litellm.proxy.utils import PrismaClient
from litellm.types.guardrails import Guardrail
- _DbOrConfigGuardrail = Union[prisma_models.LiteLLM_GuardrailsTable, Guardrail]
- _DailyMetricsRow = Union[prisma_models.LiteLLM_DailyGuardrailMetrics, prisma_models.LiteLLM_DailyPolicyMetrics]
+ _DbOrConfigGuardrail = prisma_models.LiteLLM_GuardrailsTable | Guardrail
+ _DailyMetricsRow = prisma_models.LiteLLM_DailyGuardrailMetrics | prisma_models.LiteLLM_DailyPolicyMetrics
router: Final = APIRouter()
diff --git a/litellm/proxy/health_endpoints/_health_endpoints.py b/litellm/proxy/health_endpoints/_health_endpoints.py
index 5eda1376d5c..521feb26ad4 100644
--- a/litellm/proxy/health_endpoints/_health_endpoints.py
+++ b/litellm/proxy/health_endpoints/_health_endpoints.py
@@ -7,7 +7,7 @@ import time
import traceback
from collections.abc import Iterable
from datetime import datetime, timedelta
-from typing import Any, Final, Literal, TypedDict, Union, cast
+from typing import Any, Final, Literal, TypedDict, cast
import fastapi
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
@@ -110,7 +110,7 @@ def get_callback_identifier(callback):
router: Final = APIRouter()
-services = Union[
+services = (
Literal[
"slack_budget_alerts",
"langfuse",
@@ -127,9 +127,9 @@ services = Union[
"galileo",
"newrelic",
"sqs",
- ],
- str,
-]
+ ]
+ | str
+)
@router.get(
diff --git a/litellm/proxy/hooks/batch_rate_limiter.py b/litellm/proxy/hooks/batch_rate_limiter.py
index d164af66cad..7e33583fc9d 100644
--- a/litellm/proxy/hooks/batch_rate_limiter.py
+++ b/litellm/proxy/hooks/batch_rate_limiter.py
@@ -19,7 +19,7 @@ Quick summary:
import json
from collections.abc import Iterable
-from typing import TYPE_CHECKING, Any, Final, Literal, NoReturn, Union
+from typing import TYPE_CHECKING, Any, Final, Literal, NoReturn
from fastapi import HTTPException
from pydantic import BaseModel
@@ -61,7 +61,7 @@ if TYPE_CHECKING:
from litellm.proxy.utils import InternalUsageCache as _InternalUsageCache
from litellm.router import Router as _Router
- Span = Union[_Span, Any]
+ Span = _Span | Any
InternalUsageCache = _InternalUsageCache
Router = _Router
ParallelRequestLimiter = _ParallelRequestLimiter
diff --git a/litellm/proxy/hooks/batch_redis_get.py b/litellm/proxy/hooks/batch_redis_get.py
index 023733acb47..13e2bdbc304 100644
--- a/litellm/proxy/hooks/batch_redis_get.py
+++ b/litellm/proxy/hooks/batch_redis_get.py
@@ -53,7 +53,7 @@ class _PROXY_BatchRedisRequests(CustomLogger):
key_value_dict = {}
in_memory_cache_exists = False
- for key in cache.in_memory_cache.cache_dict.keys():
+ for key in cache.in_memory_cache.cache_dict:
if isinstance(key, str) and key.startswith(cache_key_name):
in_memory_cache_exists = True
diff --git a/litellm/proxy/hooks/litellm_skills/main.py b/litellm/proxy/hooks/litellm_skills/main.py
index 8a4953fa324..dd61cad15a1 100644
--- a/litellm/proxy/hooks/litellm_skills/main.py
+++ b/litellm/proxy/hooks/litellm_skills/main.py
@@ -170,7 +170,7 @@ class SkillsInjectionHook(CustomLogger):
skill_files = self.prompt_handler.extract_all_files(skill)
if skill_files:
all_skill_files[skill.skill_id] = skill_files
- for path in skill_files.keys():
+ for path in skill_files:
if path.endswith(".py"):
all_module_paths.append(path)
@@ -238,7 +238,7 @@ class SkillsInjectionHook(CustomLogger):
if skill_files:
all_skill_files[skill.skill_id] = skill_files
# Collect Python module paths
- for path in skill_files.keys():
+ for path in skill_files:
if path.endswith(".py"):
all_module_paths.append(path)
diff --git a/litellm/proxy/hooks/parallel_request_limiter.py b/litellm/proxy/hooks/parallel_request_limiter.py
index 3755626ae35..79c85571fc9 100644
--- a/litellm/proxy/hooks/parallel_request_limiter.py
+++ b/litellm/proxy/hooks/parallel_request_limiter.py
@@ -1,7 +1,7 @@
import asyncio
import sys
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING, Any, Final, Literal, NoReturn, Union
+from typing import TYPE_CHECKING, Any, Final, Literal, NoReturn
from pydantic import BaseModel
from typing_extensions import TypedDict
@@ -26,7 +26,7 @@ if TYPE_CHECKING:
from litellm.proxy.utils import InternalUsageCache as _InternalUsageCache
- Span = Union[_Span, Any]
+ Span = _Span | Any
InternalUsageCache = _InternalUsageCache
else:
Span = Any
diff --git a/litellm/proxy/hooks/parallel_request_limiter_v3.py b/litellm/proxy/hooks/parallel_request_limiter_v3.py
index 2725da1ee12..395058bf976 100644
--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py
+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py
@@ -12,7 +12,7 @@ from collections.abc import Callable
from contextvars import ContextVar
from dataclasses import dataclass, field
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final, Literal, TypedDict, Union, cast
+from typing import TYPE_CHECKING, Any, Final, Literal, TypedDict, cast
from litellm import DualCache
from litellm._logging import verbose_proxy_logger
@@ -49,7 +49,7 @@ if TYPE_CHECKING:
from litellm.proxy.utils import InternalUsageCache as _InternalUsageCache
from litellm.types.caching import RedisPipelineIncrementOperation
- Span = Union[_Span, Any]
+ Span = _Span | Any
InternalUsageCache = _InternalUsageCache
else:
Span = Any
diff --git a/litellm/proxy/management_endpoints/cache_settings_endpoints.py b/litellm/proxy/management_endpoints/cache_settings_endpoints.py
index fc0803d08ea..50637208e03 100644
--- a/litellm/proxy/management_endpoints/cache_settings_endpoints.py
+++ b/litellm/proxy/management_endpoints/cache_settings_endpoints.py
@@ -249,7 +249,7 @@ def _redact_settings(settings: Mapping[str, object] | None) -> dict[str, object]
"""
if not settings:
return {}
- return {k: _REDACTED_VALUE for k in settings.keys()}
+ return {k: _REDACTED_VALUE for k in settings}
def _log_audit_task_exception(task: "asyncio.Task[None]") -> None:
diff --git a/litellm/proxy/management_endpoints/common_daily_activity.py b/litellm/proxy/management_endpoints/common_daily_activity.py
index 095f83363b0..96f2465ebb9 100644
--- a/litellm/proxy/management_endpoints/common_daily_activity.py
+++ b/litellm/proxy/management_endpoints/common_daily_activity.py
@@ -2,7 +2,7 @@ import asyncio
from collections.abc import Awaitable, Callable, Mapping, Sequence
from datetime import datetime
from types import SimpleNamespace
-from typing import TYPE_CHECKING, Final, Protocol, Union
+from typing import TYPE_CHECKING, Final, Protocol
from fastapi import HTTPException, status
from typing_extensions import TypedDict
@@ -109,7 +109,7 @@ class _KeyMetadataDict(TypedDict, total=False):
team_id: str | None
-_WhereValue = Union[str, dict[str, object]]
+_WhereValue = str | dict[str, object]
class _AggregatedSpendData(TypedDict):
diff --git a/litellm/proxy/management_endpoints/config_override_endpoints.py b/litellm/proxy/management_endpoints/config_override_endpoints.py
index ae08efe267c..06184cb40fa 100644
--- a/litellm/proxy/management_endpoints/config_override_endpoints.py
+++ b/litellm/proxy/management_endpoints/config_override_endpoints.py
@@ -54,7 +54,7 @@ def _redact_config(config: Mapping[str, Any] | None) -> dict[str, Any]:
"""
if not config:
return {}
- return {k: _AUDIT_REDACTED for k in config.keys()}
+ return {k: _AUDIT_REDACTED for k in config}
def _log_audit_task_exception(task: "asyncio.Task[None]") -> None:
diff --git a/litellm/proxy/management_endpoints/customer_endpoints.py b/litellm/proxy/management_endpoints/customer_endpoints.py
index a983e859b48..a51ff48aab6 100644
--- a/litellm/proxy/management_endpoints/customer_endpoints.py
+++ b/litellm/proxy/management_endpoints/customer_endpoints.py
@@ -365,7 +365,7 @@ async def new_end_user(
_user_data: Final = data.dict(exclude_none=True)
for k, v in _user_data.items():
- if k not in BudgetNewRequest.model_fields.keys():
+ if k not in BudgetNewRequest.model_fields:
new_end_user_obj[k] = v
## Handle Object Permission - MCP Servers, Vector Stores etc.
@@ -573,10 +573,10 @@ async def update_end_user(
# budget_id is for linking to existing budget, not for creating new budget
if k == "budget_id":
update_end_user_table_data[k] = v
- elif k in LiteLLM_BudgetTable.model_fields.keys():
+ elif k in LiteLLM_BudgetTable.model_fields:
budget_table_data[k] = v
- elif k in LiteLLM_EndUserTable.model_fields.keys():
+ elif k in LiteLLM_EndUserTable.model_fields:
update_end_user_table_data[k] = v
## Handle object permission updates (MCP servers, vector stores, etc.)
diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py
index 97b4ec76c50..e2f4af150f5 100644
--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py
+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py
@@ -584,7 +584,7 @@ async def new_user(
special_keys: Final = ["token", "token_id"]
response_dict: Final = {}
for key, value in response.items():
- if key in NewUserResponse.model_fields.keys() and key not in special_keys:
+ if key in NewUserResponse.model_fields and key not in special_keys:
response_dict[key] = value
response_dict["key"] = response.get("token", "")
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index e4def45892b..e280e470aff 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -214,7 +214,7 @@ async def _check_custom_key_allowed(custom_key_value: str | None) -> None:
)
-def _is_team_key(data: Union[GenerateKeyRequest, LiteLLM_VerificationToken]):
+def _is_team_key(data: GenerateKeyRequest | LiteLLM_VerificationToken):
return data.team_id is not None
@@ -497,7 +497,7 @@ def key_generation_check(
def common_key_access_checks(
user_api_key_dict: UserAPIKeyAuth,
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
llm_router: Router | None,
premium_user: bool,
user_id: str | None = None,
@@ -751,7 +751,7 @@ _BUDGET_NUMERIC_KEYS = frozenset(["max_budget", "soft_budget", "max_parallel_req
def _enforce_upperbound_key_params(
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
fill_defaults: bool = True,
) -> None:
"""
@@ -1160,7 +1160,7 @@ async def _common_key_generation_helper(
def _check_key_model_specific_limits(
keys: list[LiteLLM_VerificationToken],
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
entity_rpm_limit: int | None,
entity_tpm_limit: int | None,
entity_model_rpm_limit_dict: dict[str, int],
@@ -1231,7 +1231,7 @@ def _check_key_model_specific_limits(
def _check_key_rpm_tpm_limits(
keys: list[LiteLLM_VerificationToken],
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
entity_rpm_limit: int | None,
entity_tpm_limit: int | None,
entity_type: str, # "team" or "organization"
@@ -1270,7 +1270,7 @@ def _check_key_rpm_tpm_limits(
def check_team_key_model_specific_limits(
keys: list[LiteLLM_VerificationToken],
team_table: LiteLLM_TeamTableCachedObj,
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
) -> None:
"""
Check if the team key is allocating model specific limits. If so, raise an error if we're overallocating.
@@ -1295,7 +1295,7 @@ def check_team_key_model_specific_limits(
def check_team_key_rpm_tpm_limits(
keys: list[LiteLLM_VerificationToken],
team_table: LiteLLM_TeamTableCachedObj,
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
) -> None:
"""
Check if the team key is allocating rpm/tpm limits. If so, raise an error if we're overallocating.
@@ -1311,7 +1311,7 @@ def check_team_key_rpm_tpm_limits(
async def _check_team_key_limits(
team_table: LiteLLM_TeamTableCachedObj,
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
prisma_client: PrismaClient,
) -> None:
"""
@@ -1347,7 +1347,7 @@ async def _check_team_key_limits(
async def _check_project_key_limits(
project_id: str,
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
prisma_client: PrismaClient,
user_api_key_cache: UserApiKeyCache,
) -> None:
@@ -1397,7 +1397,7 @@ async def _check_project_key_limits(
def check_org_key_model_specific_limits(
keys: list[LiteLLM_VerificationToken],
org_table: LiteLLM_OrganizationTable,
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
) -> None:
"""
Check if the organization key is allocating model specific limits. If so, raise an error if we're overallocating.
@@ -1430,7 +1430,7 @@ def check_org_key_model_specific_limits(
def check_org_key_rpm_tpm_limits(
keys: list[LiteLLM_VerificationToken],
org_table: LiteLLM_OrganizationTable,
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
) -> None:
"""
Check if the organization key is allocating rpm/tpm limits. If so, raise an error if we're overallocating.
@@ -1486,7 +1486,7 @@ async def _validate_caller_can_assign_key_org(
async def _check_org_key_limits(
org_table: LiteLLM_OrganizationTable,
- data: Union[GenerateKeyRequest, UpdateKeyRequest],
+ data: GenerateKeyRequest | UpdateKeyRequest,
prisma_client: PrismaClient,
) -> None:
"""
@@ -1943,7 +1943,7 @@ def prepare_metadata_fields(data: BaseModel, non_default_values: dict, existing_
async def prepare_key_update_data(
- data: Union[UpdateKeyRequest, RegenerateKeyRequest],
+ data: UpdateKeyRequest | RegenerateKeyRequest,
existing_key_row: LiteLLM_VerificationToken,
):
data_json: Final[dict] = data.model_dump(exclude_unset=True)
@@ -5671,7 +5671,7 @@ def _build_key_filter_conditions(
agent_id: str | None = None,
use_substring_matching: bool = False,
expires_filter: str | None = None,
-) -> dict[str, Union[str, dict[str, Any], list[dict[str, Any]]]]:
+) -> dict[str, str | dict[str, Any] | list[dict[str, Any]]]:
"""Build filter conditions for key listing.
Visibility rules:
@@ -5683,7 +5683,7 @@ def _build_key_filter_conditions(
so former members cannot see service accounts they created after leaving.
"""
# Prepare filter conditions
- where: dict[str, Union[str, dict[str, Any], list[dict[str, Any]]]] = {}
+ where: dict[str, str | dict[str, Any] | list[dict[str, Any]]] = {}
where.update(_get_condition_to_filter_out_ui_session_tokens())
# Build the OR conditions for user's keys and admin team keys
@@ -5917,7 +5917,7 @@ async def _list_key_helper(
user_map = {user.user_id: user for user in users}
# Prepare response
- key_list: Final[list[Union[str, UserAPIKeyAuth, LiteLLM_DeletedVerificationToken]]] = []
+ key_list: Final[list[str | UserAPIKeyAuth | LiteLLM_DeletedVerificationToken]] = []
for key in keys:
# Convert Prisma model to dict (supports both Pydantic v1 and v2)
try:
diff --git a/litellm/proxy/management_endpoints/organization_endpoints.py b/litellm/proxy/management_endpoints/organization_endpoints.py
index f64c2da9bff..3ae871b476e 100644
--- a/litellm/proxy/management_endpoints/organization_endpoints.py
+++ b/litellm/proxy/management_endpoints/organization_endpoints.py
@@ -696,7 +696,7 @@ async def update_organization(
# Handle budget updates if budget fields are provided
budget_fields: Final = {
- k: v for k, v in data.model_dump().items() if k in LiteLLM_BudgetTable.model_fields.keys() and v is not None
+ k: v for k, v in data.model_dump().items() if k in LiteLLM_BudgetTable.model_fields and v is not None
}
if budget_fields and existing_organization_row.budget_id:
@@ -706,7 +706,7 @@ async def update_organization(
)
# Remove budget fields from organization update data
- for field in LiteLLM_BudgetTable.model_fields.keys():
+ for field in LiteLLM_BudgetTable.model_fields:
updated_organization_row.pop(field, None)
response: Final = await _table(OrganizationRepository(prisma_client)).update(
diff --git a/litellm/proxy/pass_through_endpoints/passthrough_guardrails.py b/litellm/proxy/pass_through_endpoints/passthrough_guardrails.py
index bb5171c1abd..de9b0acf081 100644
--- a/litellm/proxy/pass_through_endpoints/passthrough_guardrails.py
+++ b/litellm/proxy/pass_through_endpoints/passthrough_guardrails.py
@@ -7,7 +7,7 @@ Handles guardrail execution for passthrough endpoints with:
- Automatic inheritance from org/team/key levels when enabled
"""
-from typing import Any, Final, Union
+from typing import Any, Final
from litellm._logging import verbose_proxy_logger
from litellm.proxy._types import (
@@ -19,10 +19,10 @@ from litellm.proxy.pass_through_endpoints.jsonpath_extractor import JsonPathExtr
# Type for raw guardrails config input (before normalization)
# Can be a list of names or a dict with settings
-PassThroughGuardrailsConfigInput = Union[
- list[str], # Simple list: ["guard-1", "guard-2"]
- PassThroughGuardrailsConfig, # Dict: {"guard-1": {"request_fields": [...]}}
-]
+PassThroughGuardrailsConfigInput = (
+ list[str] # Simple list: ["guard-1", "guard-2"]
+ | PassThroughGuardrailsConfig # Dict: {"guard-1": {"request_fields": [...]}}
+)
class PassthroughGuardrailHandler:
@@ -246,7 +246,7 @@ class PassthroughGuardrailHandler:
guardrails_to_run: Final[dict[str, bool]] = {}
# Add passthrough-specific guardrails
- for guardrail_name in normalized_config.keys():
+ for guardrail_name in normalized_config:
guardrails_to_run[guardrail_name] = True
verbose_proxy_logger.debug("Added passthrough-specific guardrail: %s", guardrail_name)
diff --git a/litellm/proxy/policy_engine/__init__.py b/litellm/proxy/policy_engine/__init__.py
index 9ef5fd02f78..18b37dc4852 100644
--- a/litellm/proxy/policy_engine/__init__.py
+++ b/litellm/proxy/policy_engine/__init__.py
@@ -47,14 +47,12 @@ from litellm.proxy.policy_engine.policy_resolver import PolicyResolver
from litellm.proxy.policy_engine.policy_validator import PolicyValidator
__all__ = [
- # Registries
- "PolicyRegistry",
- "get_policy_registry",
"AttachmentRegistry",
- "get_attachment_registry",
- # Core components
+ "ConditionEvaluator",
"PolicyMatcher",
+ "PolicyRegistry",
"PolicyResolver",
"PolicyValidator",
- "ConditionEvaluator",
+ "get_attachment_registry",
+ "get_policy_registry",
]
diff --git a/litellm/proxy/prompts/prompt_registry.py b/litellm/proxy/prompts/prompt_registry.py
index 72bb582cedc..695bdabfe83 100644
--- a/litellm/proxy/prompts/prompt_registry.py
+++ b/litellm/proxy/prompts/prompt_registry.py
@@ -180,7 +180,7 @@ class InMemoryPromptRegistry:
from litellm.proxy.prompts.prompt_endpoints import get_base_prompt_id
prompts_to_delete: Final = [
- pid for pid in self.IN_MEMORY_PROMPTS.keys() if get_base_prompt_id(prompt_id=pid) == base_prompt_id
+ pid for pid in self.IN_MEMORY_PROMPTS if get_base_prompt_id(prompt_id=pid) == base_prompt_id
]
for pid in prompts_to_delete:
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 3cb2f795c61..cec7f6c61df 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -130,7 +130,7 @@ if TYPE_CHECKING:
from litellm.integrations.opentelemetry import OpenTelemetry
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
OpenTelemetry = Any
@@ -640,7 +640,6 @@ except Exception:
version = "0.0.0"
litellm.suppress_debug_info = True
import json
-from typing import Union
from fastapi import (
Depends,
@@ -6679,7 +6678,7 @@ class ProxyConfig:
await evict_config_param("anthropic_beta_headers_reload_config")
# Count providers in config
- provider_count = sum(1 for k in new_config.keys() if k != "provider_aliases" and k != "description")
+ provider_count = sum(1 for k in new_config if k != "provider_aliases" and k != "description")
verbose_proxy_logger.info(
"Anthropic beta headers config reloaded successfully. Providers: %s", provider_count
)
@@ -15188,7 +15187,7 @@ async def get_config_general_settings(
)
-GeneralSettingsUILiteLLMValue = Union[float, bool, str, None]
+GeneralSettingsUILiteLLMValue = float | bool | str | None
class GeneralSettingsUILiteLLMFieldSpec(TypedDict):
@@ -16122,7 +16121,7 @@ async def reload_anthropic_beta_headers(
)
await invalidate_config_param("anthropic_beta_headers_reload_config")
- provider_count: Final = sum(1 for k in new_config.keys() if k not in ["provider_aliases", "description"])
+ provider_count: Final = sum(1 for k in new_config if k not in ["provider_aliases", "description"])
verbose_proxy_logger.info(
"Anthropic beta headers config reloaded successfully in current pod. Providers: %s", provider_count
)
diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.py
index aa4eb6e71e4..8d2569b2229 100644
--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py
+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py
@@ -123,9 +123,7 @@ def _get_spend_logs_metadata(
)
# Filter the metadata dictionary to include only the specified keys
- clean_metadata: Final = SpendLogsMetadata(
- **{key: metadata.get(key) for key in SpendLogsMetadata.__annotations__.keys()}
- )
+ clean_metadata: Final = SpendLogsMetadata(**{key: metadata.get(key) for key in SpendLogsMetadata.__annotations__})
raw_user_api_key: Final = clean_metadata.get("user_api_key")
if raw_user_api_key is not None and isinstance(raw_user_api_key, str):
clean_metadata["user_api_key"] = _hash_api_key_for_spend_log(raw_user_api_key)
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 8d638dedff8..93080b725fa 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -167,7 +167,7 @@ if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.proxy.db.spend_log_tool_index import ToolUsageTransaction
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/repositories/base_repository.py b/litellm/repositories/base_repository.py
index f497b4acde0..7008099fe8c 100644
--- a/litellm/repositories/base_repository.py
+++ b/litellm/repositories/base_repository.py
@@ -4,7 +4,7 @@ Base repository class with common functionality.
from abc import ABC, abstractmethod
from collections.abc import Iterable, Mapping, Sequence
-from typing import Any, Final, Generic, Protocol, TypeVar, Union, runtime_checkable
+from typing import Any, Final, Generic, Protocol, TypeVar, runtime_checkable
from pydantic import BaseModel
@@ -21,12 +21,7 @@ class SupportsDict(Protocol):
def dict(self) -> dict[str, object]: ...
-DbRecord = Union[
- Mapping[str, object],
- SupportsModelDump,
- SupportsDict,
- Sequence[tuple[str, object]],
-]
+DbRecord = Mapping[str, object] | SupportsModelDump | SupportsDict | Sequence[tuple[str, object]]
def record_to_dict(record: DbRecord) -> Mapping[str, object]:
diff --git a/litellm/router.py b/litellm/router.py
index 39d5080a33d..d3d390f3acc 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -30,7 +30,6 @@ from openai import AsyncOpenAI
from typing_extensions import overload
import litellm
-import litellm.litellm_core_utils
import litellm.litellm_core_utils.exception_mapping_utils
from litellm import get_secret_str
from litellm._logging import verbose_router_logger
@@ -241,7 +240,7 @@ if TYPE_CHECKING:
ResponsesAPIResponse,
)
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
AutoRouter = Any
@@ -3410,9 +3409,7 @@ class Router:
# Await the first task to complete successfully
while pending_tasks:
- done, pending_tasks = await asyncio.wait(
- pending_tasks, return_when=asyncio.FIRST_COMPLETED
- )
+ done, pending_tasks = await asyncio.wait(pending_tasks, return_when=asyncio.FIRST_COMPLETED)
for completed_task in done:
result = await check_response(completed_task)
@@ -5240,9 +5237,7 @@ class Router:
# Update kwargs with the current model name or any other model-specific adjustments
## SET CUSTOM PROVIDER TO SELECTED DEPLOYMENT ##
if not custom_llm_provider:
- _, custom_llm_provider, _, _ = get_llm_provider(
- model=model
- )
+ _, custom_llm_provider, _, _ = get_llm_provider(model=model)
new_kwargs: Final = safe_deep_copy(kwargs)
self._update_kwargs_with_deployment(
deployment=cast(dict, model_name),
@@ -6029,9 +6024,7 @@ class Router:
raise Exception(
"'custom_llm_provider' must be set. Either via:\n `Router(assistants_config={'custom_llm_provider': ..})` \nor\n `router.arun_thread(custom_llm_provider=..)`"
)
- return await original_function(
- custom_llm_provider=custom_llm_provider, client=client, **kwargs
- )
+ return await original_function(custom_llm_provider=custom_llm_provider, client=client, **kwargs)
#### [END] ASSISTANTS API ####
@@ -6359,14 +6352,9 @@ class Router:
if hasattr(original_exception, "message") and litellm.expose_router_debug_in_errors:
# add the available fallbacks to the exception
- original_exception.message += ". Received Model Group={}\nAvailable Model Group Fallbacks={}".format(
- model_group,
- mask_sensitive_structure(fallback_model_group),
- )
+ original_exception.message += f". Received Model Group={model_group}\nAvailable Model Group Fallbacks={mask_sensitive_structure(fallback_model_group)}"
if len(fallback_failure_exception_str) > 0:
- original_exception.message += (
- f"\nError doing the fallback: {fallback_failure_exception_str}"
- )
+ original_exception.message += f"\nError doing the fallback: {fallback_failure_exception_str}"
raise original_exception
@@ -7497,7 +7485,7 @@ class Router:
litellm_params=litellm_params,
model_info=_model_info,
)
- for field in CustomPricingLiteLLMParams.model_fields.keys():
+ for field in CustomPricingLiteLLMParams.model_fields:
if deployment.litellm_params.get(field) is not None:
_model_info[field] = deployment.litellm_params[field]
@@ -8246,7 +8234,7 @@ class Router:
self._add_deployment(deployment=deployment)
_model_info_dict: Final[dict] = deployment.model_info.model_dump(exclude_none=True)
- for field in CustomPricingLiteLLMParams.model_fields.keys():
+ for field in CustomPricingLiteLLMParams.model_fields:
field_value = deployment.litellm_params.get(field)
if field_value is not None:
_model_info_dict[field] = field_value
@@ -9124,9 +9112,7 @@ class Router:
and model_info["supports_parallel_function_calling"] is True
):
model_group_info.supports_parallel_function_calling = True
- if (
- model_info.get("supports_vision", None) is not None and model_info["supports_vision"] is True
- ):
+ if model_info.get("supports_vision", None) is not None and model_info["supports_vision"] is True:
model_group_info.supports_vision = True
if (
model_info.get("supports_function_calling", None) is not None
@@ -9144,9 +9130,7 @@ class Router:
):
model_group_info.supports_url_context = True
- if (
- model_info.get("supports_reasoning", None) is not None and model_info["supports_reasoning"] is True
- ):
+ if model_info.get("supports_reasoning", None) is not None and model_info["supports_reasoning"] is True:
model_group_info.supports_reasoning = True
if (
model_info.get("supported_openai_params", None) is not None
@@ -9495,7 +9479,7 @@ class Router:
else:
# When model_name is None, return all model IDs
# Use the index map keys for O(n) where n = total deployments
- for model_id in self.model_id_to_deployment_index_map.keys():
+ for model_id in self.model_id_to_deployment_index_map:
idx = self.model_id_to_deployment_index_map[model_id]
model = self.model_list[idx]
if "model_info" in model and "id" in model["model_info"]:
@@ -10876,9 +10860,7 @@ class Router:
args=(e, traceback_exception),
).start() # log response
# Handle any exceptions that might occur during streaming
- asyncio.create_task(
- logging_obj.async_failure_handler(e, traceback_exception)
- )
+ asyncio.create_task(logging_obj.async_failure_handler(e, traceback_exception))
raise e
async def async_get_available_deployment_for_pass_through(
@@ -11003,9 +10985,7 @@ class Router:
target=logging_obj.failure_handler,
args=(e, traceback_exception),
).start()
- asyncio.create_task(
- logging_obj.async_failure_handler(e, traceback_exception)
- )
+ asyncio.create_task(logging_obj.async_failure_handler(e, traceback_exception))
raise e
async def _run_routing_plugins(
diff --git a/litellm/router_strategy/lowest_latency.py b/litellm/router_strategy/lowest_latency.py
index 5db2e64598c..eebe81ebba1 100644
--- a/litellm/router_strategy/lowest_latency.py
+++ b/litellm/router_strategy/lowest_latency.py
@@ -2,7 +2,7 @@
# picks based on response time (for streaming, this is time to first token)
import random
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
import litellm
from litellm import ModelResponse, token_counter, verbose_logger
@@ -14,7 +14,7 @@ from litellm.types.utils import LiteLLMPydanticObjectBase
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/router_strategy/lowest_tpm_rpm_v2.py b/litellm/router_strategy/lowest_tpm_rpm_v2.py
index a1656caa066..6deba5aa1cf 100644
--- a/litellm/router_strategy/lowest_tpm_rpm_v2.py
+++ b/litellm/router_strategy/lowest_tpm_rpm_v2.py
@@ -1,7 +1,7 @@
#### What this does ####
# identifies lowest tpm deployment
import random
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
import httpx
@@ -20,7 +20,7 @@ from .base_routing_strategy import BaseRoutingStrategy
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/router_utils/cooldown_cache.py b/litellm/router_utils/cooldown_cache.py
index 73eb441092c..8d3b897ae3e 100644
--- a/litellm/router_utils/cooldown_cache.py
+++ b/litellm/router_utils/cooldown_cache.py
@@ -4,7 +4,7 @@ Wrapper around router cache. Meant to handle model cooldown logic
import functools
import time
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from typing_extensions import TypedDict
@@ -16,7 +16,7 @@ from litellm.litellm_core_utils.sensitive_data_masker import SensitiveDataMasker
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/router_utils/cooldown_handlers.py b/litellm/router_utils/cooldown_handlers.py
index ee67c74fb4c..2b26928a21c 100644
--- a/litellm/router_utils/cooldown_handlers.py
+++ b/litellm/router_utils/cooldown_handlers.py
@@ -8,7 +8,7 @@ Router cooldown handlers
import asyncio
import math
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
import litellm
from litellm._logging import verbose_router_logger
@@ -31,7 +31,7 @@ if TYPE_CHECKING:
from litellm.router import Router as _Router
LitellmRouter = _Router
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
LitellmRouter = Any
Span = Any
diff --git a/litellm/router_utils/fallback_event_handlers.py b/litellm/router_utils/fallback_event_handlers.py
index 2da7d404ed2..1c6bb52ccb8 100644
--- a/litellm/router_utils/fallback_event_handlers.py
+++ b/litellm/router_utils/fallback_event_handlers.py
@@ -237,7 +237,7 @@ def _check_non_standard_fallback_format(fallbacks: list[Any] | None) -> bool:
return True
elif all(isinstance(item, dict) for item in fallbacks):
for item in fallbacks:
- for key in LiteLLMParamsTypedDict.__annotations__.keys():
+ for key in LiteLLMParamsTypedDict.__annotations__:
if key in item:
# If the value is a list, it's likely a standard fallback model group mapping
# (e.g. {"model": ["backup"]}) rather than a parameter override.
diff --git a/litellm/router_utils/handle_error.py b/litellm/router_utils/handle_error.py
index d6552a67fcd..0e7490d31b1 100644
--- a/litellm/router_utils/handle_error.py
+++ b/litellm/router_utils/handle_error.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from litellm._logging import redact_secrets, verbose_router_logger
from litellm.constants import MAX_EXCEPTION_MESSAGE_LENGTH
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
from litellm.router import Router as _Router
LitellmRouter = _Router
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
LitellmRouter = Any
Span = Any
diff --git a/litellm/router_utils/health_state_cache.py b/litellm/router_utils/health_state_cache.py
index cfd5ef85af7..95094f7abfa 100644
--- a/litellm/router_utils/health_state_cache.py
+++ b/litellm/router_utils/health_state_cache.py
@@ -6,7 +6,7 @@ and exposes it for router candidate filtering.
"""
import time
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
from typing_extensions import TypedDict
@@ -16,7 +16,7 @@ from litellm.caching.caching import DualCache
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/router_utils/pre_call_checks/model_rate_limit_check.py b/litellm/router_utils/pre_call_checks/model_rate_limit_check.py
index 6bbc9c9eff5..af3d7ddfac7 100644
--- a/litellm/router_utils/pre_call_checks/model_rate_limit_check.py
+++ b/litellm/router_utils/pre_call_checks/model_rate_limit_check.py
@@ -11,7 +11,7 @@ is logged the first time such a deployment is seen.
"""
import contextlib
-from typing import TYPE_CHECKING, Any, Final, Union
+from typing import TYPE_CHECKING, Any, Final
import httpx
@@ -37,7 +37,7 @@ from litellm.utils import get_utc_datetime
if TYPE_CHECKING:
from opentelemetry.trace import Span as _Span
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
diff --git a/litellm/router_utils/prompt_caching_cache.py b/litellm/router_utils/prompt_caching_cache.py
index f7fe07d849b..817c008fad3 100644
--- a/litellm/router_utils/prompt_caching_cache.py
+++ b/litellm/router_utils/prompt_caching_cache.py
@@ -4,7 +4,7 @@ Wrapper around router cache. Meant to store model id when prompt caching support
import hashlib
import json
-from typing import TYPE_CHECKING, Any, Final, Union, cast
+from typing import TYPE_CHECKING, Any, Final, cast
from typing_extensions import TypedDict
@@ -18,7 +18,7 @@ if TYPE_CHECKING:
from litellm.router import Router
litellm_router = Router
- Span = Union[_Span, Any]
+ Span = _Span | Any
else:
Span = Any
litellm_router = Any
diff --git a/litellm/types/integrations/prometheus.py b/litellm/types/integrations/prometheus.py
index 2d453aac009..ebec5df55fa 100644
--- a/litellm/types/integrations/prometheus.py
+++ b/litellm/types/integrations/prometheus.py
@@ -837,10 +837,12 @@ class PrometheusMetricLabels:
return default_labels + custom_labels
-_USER_API_KEY_LABEL_VALUE_INIT_ALIASES: Final[dict[str, str]] = {
- # Some tests / call sites use ``api_key_hash``; Prometheus field is ``hashed_api_key``.
- "api_key_hash": "hashed_api_key",
-}
+_USER_API_KEY_LABEL_VALUE_INIT_ALIASES: Final[Mapping[str, str]] = MappingProxyType(
+ {
+ # Some tests / call sites use ``api_key_hash``; Prometheus field is ``hashed_api_key``.
+ "api_key_hash": "hashed_api_key",
+ }
+)
@dataclass(frozen=True, init=False)
diff --git a/litellm/types/llms/anthropic_tool_search.py b/litellm/types/llms/anthropic_tool_search.py
index 160326fca40..f613caf9713 100644
--- a/litellm/types/llms/anthropic_tool_search.py
+++ b/litellm/types/llms/anthropic_tool_search.py
@@ -4,6 +4,8 @@ Tool Search Beta Header Configuration
Reference: https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool
"""
+from collections.abc import Mapping
+from types import MappingProxyType
from typing import Final
from litellm.types.utils import LlmProviders
@@ -15,14 +17,16 @@ TOOL_SEARCH_BETA_HEADER_BEDROCK: Final = "tool-search-tool-2025-10-19"
# Mapping of custom_llm_provider -> tool search beta header
-TOOL_SEARCH_BETA_HEADER_BY_PROVIDER: Final[dict[str, str]] = {
- LlmProviders.ANTHROPIC.value: TOOL_SEARCH_BETA_HEADER_ANTHROPIC,
- LlmProviders.AZURE.value: TOOL_SEARCH_BETA_HEADER_ANTHROPIC,
- LlmProviders.AZURE_AI.value: TOOL_SEARCH_BETA_HEADER_ANTHROPIC,
- LlmProviders.VERTEX_AI.value: TOOL_SEARCH_BETA_HEADER_VERTEX,
- LlmProviders.VERTEX_AI_BETA.value: TOOL_SEARCH_BETA_HEADER_VERTEX,
- LlmProviders.BEDROCK.value: TOOL_SEARCH_BETA_HEADER_BEDROCK,
-}
+TOOL_SEARCH_BETA_HEADER_BY_PROVIDER: Final[Mapping[str, str]] = MappingProxyType(
+ {
+ LlmProviders.ANTHROPIC.value: TOOL_SEARCH_BETA_HEADER_ANTHROPIC,
+ LlmProviders.AZURE.value: TOOL_SEARCH_BETA_HEADER_ANTHROPIC,
+ LlmProviders.AZURE_AI.value: TOOL_SEARCH_BETA_HEADER_ANTHROPIC,
+ LlmProviders.VERTEX_AI.value: TOOL_SEARCH_BETA_HEADER_VERTEX,
+ LlmProviders.VERTEX_AI_BETA.value: TOOL_SEARCH_BETA_HEADER_VERTEX,
+ LlmProviders.BEDROCK.value: TOOL_SEARCH_BETA_HEADER_BEDROCK,
+ }
+)
def get_tool_search_beta_header(custom_llm_provider: str) -> str:
diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/block_code_execution.py b/litellm/types/proxy/guardrails/guardrail_hooks/block_code_execution.py
index 2a24de6c73b..d74d9b2ef94 100644
--- a/litellm/types/proxy/guardrails/guardrail_hooks/block_code_execution.py
+++ b/litellm/types/proxy/guardrails/guardrail_hooks/block_code_execution.py
@@ -1,6 +1,6 @@
"""Types for the Block Code Execution guardrail."""
-from typing import Any, Final, Literal, TypedDict, cast
+from typing import Final, Literal, TypedDict
from pydantic import Field
@@ -45,10 +45,7 @@ class BlockCodeExecutionGuardrailConfigModel(GuardrailConfigModel):
blocked_languages: list[str] | None = Field(
default=None,
description="Language tags to block (e.g. python, javascript, bash). Empty or None = block all fenced code blocks.",
- json_schema_extra=cast(
- Any,
- {"ui_type": "multiselect", "options": BLOCKED_LANGUAGES_OPTIONS},
- ),
+ json_schema_extra={"ui_type": "multiselect", "options": list(BLOCKED_LANGUAGES_OPTIONS)},
)
action: Literal["block", "mask"] = Field(
default="block",
@@ -59,16 +56,13 @@ class BlockCodeExecutionGuardrailConfigModel(GuardrailConfigModel):
ge=0.0,
le=1.0,
description="Only block or mask when detection confidence >= this value; below threshold, allow or log_only.",
- json_schema_extra=cast(
- Any,
- {
- "ui_type": "percentage",
- "min": 0.0,
- "max": 1.0,
- "step": 0.1,
- "default_value": 0.5,
- },
- ),
+ json_schema_extra={
+ "ui_type": "percentage",
+ "min": 0.0,
+ "max": 1.0,
+ "step": 0.1,
+ "default_value": 0.5,
+ },
)
detect_execution_intent: bool = Field(
default=True,
diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/xecguard.py b/litellm/types/proxy/guardrails/guardrail_hooks/xecguard.py
index be97e49b837..74a95898cb3 100644
--- a/litellm/types/proxy/guardrails/guardrail_hooks/xecguard.py
+++ b/litellm/types/proxy/guardrails/guardrail_hooks/xecguard.py
@@ -1,4 +1,4 @@
-from typing import Any, Final, Literal, cast
+from typing import Final, Literal
from pydantic import Field
@@ -43,13 +43,10 @@ class XecGuardConfigModel(GuardrailConfigModel):
"the guardrail defaults to System Prompt Enforcement + "
"Harmful Content Protection."
),
- json_schema_extra=cast(
- Any,
- {
- "ui_type": "multiselect",
- "options": XECGUARD_DEFAULT_POLICY_OPTIONS,
- },
- ),
+ json_schema_extra={
+ "ui_type": "multiselect",
+ "options": list(XECGUARD_DEFAULT_POLICY_OPTIONS),
+ },
)
block_on_error: bool | None = Field(
default=None,
diff --git a/litellm/utils.py b/litellm/utils.py
index 19c3d10695a..ee821b6bf5d 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -766,16 +766,8 @@ def function_setup(
if (
len(litellm.input_callback) > 0 or len(litellm.success_callback) > 0 or len(litellm.failure_callback) > 0
- ) and len(
- callback_list
- ) == 0:
- callback_list = list(
- set(
- litellm.input_callback
- + litellm.success_callback
- + litellm.failure_callback
- )
- )
+ ) and len(callback_list) == 0:
+ callback_list = list(set(litellm.input_callback + litellm.success_callback + litellm.failure_callback))
get_set_callbacks: Final = getattr(sys.modules[__name__], "get_set_callbacks")
get_set_callbacks()(callback_list=callback_list, function_id=function_id)
## ASYNC CALLBACKS - safety net for callbacks added via direct append
@@ -3093,7 +3085,7 @@ def get_optional_params_embeddings(
if supported_params is None:
return
unsupported_params: Final = {}
- for k in non_default_params.keys():
+ for k in non_default_params:
if k not in supported_params:
unsupported_params[k] = non_default_params[k]
if unsupported_params:
@@ -3148,7 +3140,7 @@ def get_optional_params_embeddings(
if (
model is not None
and "text-embedding-3" not in model
- and "dimensions" in non_default_params.keys()
+ and "dimensions" in non_default_params
and "dimensions" not in (allowed_openai_params or [])
):
# Honor drop_params (per-call) and litellm.drop_params (global) the same
@@ -3839,7 +3831,7 @@ def get_optional_params(
verbose_logger.debug("\nLiteLLM: Params passed to completion() %s", passed_params)
verbose_logger.debug("\nLiteLLM: Non-Default params passed to completion() %s", non_default_params)
unsupported_params: Final = {}
- for k in non_default_params.keys():
+ for k in non_default_params:
if k not in supported_params:
if k == "user" or k == "stream_options" or k == "stream":
continue
@@ -4255,7 +4247,7 @@ def get_optional_params(
drop_params=(drop_params if drop_params is not None and isinstance(drop_params, bool) else False),
)
# WatsonX-text param check
- for param in passed_params.keys():
+ for param in passed_params:
if litellm.IBMWatsonXAIConfig().is_watsonx_text_param(param):
raise ValueError(
f"LiteLLM now defaults to Watsonx's `/text/chat` endpoint. Please use the `watsonx_text` provider instead, to call the `/text/generation` endpoint. Param: {param}"
diff --git a/litellm/vector_store_files/main.py b/litellm/vector_store_files/main.py
index 846eebe8d1d..7af8dc7d435 100644
--- a/litellm/vector_store_files/main.py
+++ b/litellm/vector_store_files/main.py
@@ -4,7 +4,7 @@ import asyncio
import contextvars
from collections.abc import Coroutine
from functools import partial
-from typing import Any, Final, Union
+from typing import Any, Final
import httpx
@@ -28,7 +28,7 @@ from litellm.vector_store_files.utils import VectorStoreFileRequestUtils
base_llm_http_handler = BaseLLMHTTPHandler()
-VectorStoreFileAttributeValue = Union[str, int, float, bool]
+VectorStoreFileAttributeValue = str | int | float | bool
VectorStoreFileAttributes = dict[str, VectorStoreFileAttributeValue]
diff --git a/ruff-strict-budget.json b/ruff-strict-budget.json
index 43b3bab97ea..0b382b2170a 100644
--- a/ruff-strict-budget.json
+++ b/ruff-strict-budget.json
@@ -111,7 +111,7 @@
"limit": 3
},
"F401": {
- "limit": 20
+ "limit": 17
},
"FURB136": {
"limit": 0
diff --git a/type-discipline-budget.json b/type-discipline-budget.json
index c3c5a5fb24a..3444be73ccd 100644
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@ -3,10 +3,10 @@
"limit": 23346
},
"LIT002": {
- "limit": 27227
+ "limit": 27224
},
"LIT003": {
- "limit": 286
+ "limit": 269
},
"LIT004": {
"limit": 43
@@ -15,7 +15,7 @@
"limit": 0
},
"LIT006": {
- "limit": 1103
+ "limit": 1102
},
"LIT007": {
"limit": 0