From 3ccc619792785f8420f35bb13f856ac6d0f5280c Mon Sep 17 00:00:00 2001 From: Mateo Wang <277851410+mateo-berri@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:25:00 +0000 Subject: [PATCH] fix(router): make the constructor stub work for mypy and guard it in CI (#50354) * fix(router): make the constructor stub work for mypy and guard it in CI Use a plain ParamSpec so mypy reads the stub, drop the dead _host parameter the Rust core already refused, type check a valid and an unknown argument in tests/e2e_harness, and run that type check when litellm Python files change. * fix(typing): read type variables as type variables in mypy and guard the Router stub in lint * fix(typing): count only the probe errors in the Router stub guard and flag Final type variables everywhere * fix(lint): run the Router stub guard and e2e type check from make check make check now runs check_router_constructor_stub.py when litellm/router.py or uv.lock changes, and the e2e basedpyright step on pyproject.toml, uv.lock, pyrightconfig.json, and litellm-proxy-extras Python, matching CI. CI's e2e type check also fires on litellm-proxy-extras Python, which tests/e2e/perf imports. LIT010 treats TypeAliasType like a type variable, since mypy also rejects a Final type alias. * fix(lint): guard the Router stub through the litellm export and keep TypeAliasType bare in LIT010 docs * test: type the new LIT010 type variable tests --- .github/workflows/test-linting.yml | 5 +- AGENTS.md | 2 +- litellm/caching/redis_batch.py | 2 +- litellm/caching/redis_cluster_cache.py | 2 +- .../google_genai/adapters/transformation.py | 2 +- .../anthropic_cache_control_hook.py | 2 +- litellm/integrations/custom_logger_v2/call.py | 4 +- .../custom_logger_v2/dispatcher.py | 2 +- .../integrations/custom_logger_v2/legacy.py | 2 +- .../integrations/custom_logger_v2/logger.py | 2 +- .../integrations/custom_logger_v2/manifest.py | 2 +- litellm/integrations/lens/queries.py | 4 +- litellm/integrations/lens/storage.py | 2 +- litellm/integrations/prometheus.py | 8 +-- .../websearch_interception/handler.py | 2 +- litellm/litellm_core_utils/asyncify.py | 2 +- litellm/litellm_core_utils/batch_utils.py | 2 +- .../chat_completion_agentic_loop.py | 2 +- litellm/litellm_core_utils/core_helpers.py | 2 +- litellm/litellm_core_utils/env_utils.py | 2 +- litellm/litellm_core_utils/litellm_logging.py | 4 +- .../prompt_templates/factory.py | 2 +- .../mid_conversation_system.py | 2 +- .../prompt_cache_breakpoint_utils.py | 4 +- litellm/litellm_core_utils/ptu_shares.py | 2 +- litellm/litellm_core_utils/single_flight.py | 4 +- .../streaming_chunk_builder_utils.py | 2 +- litellm/litellm_core_utils/token_counter.py | 4 +- litellm/litellm_core_utils/tool_fields.py | 8 +-- .../messages/adapters/transformation.py | 2 +- .../context_management/editors/compact.py | 2 +- litellm/llms/anthropic/messages/utils.py | 2 +- .../llms/bedrock/chat/converse_to_openai.py | 2 +- litellm/llms/bedrock/chat/invoke_handler.py | 2 +- .../guardrail_translation/handler.py | 2 +- .../bedrock/passthrough/transformation.py | 2 +- litellm/llms/custom_httpx/http_handler.py | 2 +- litellm/llms/minimax/videos/transformation.py | 2 +- .../guardrail_translation/handler.py | 4 +- litellm/llms/openai_like/common_utils.py | 2 +- .../decisions/transformation.py | 2 +- litellm/llms/vertex_ai/common_utils.py | 2 +- .../context_caching/rejected_cache_retry.py | 4 +- litellm/llms/vertex_ai/gemini/long_decode.py | 2 +- .../rejected_thought_signature_retry.py | 4 +- litellm/llms/vertex_ai/request_labels.py | 2 +- .../llms/volcengine/videos/transformation.py | 2 +- litellm/proxy/auth/model_checks.py | 2 +- litellm/proxy/bug_report_config.py | 2 +- litellm/proxy/client/cli/commands/agents.py | 6 +- litellm/proxy/client/cli/commands/auth.py | 2 +- litellm/proxy/common_request_processing.py | 6 +- .../common_utils/codex_catalog_source.py | 2 +- .../common_utils/encrypt_decrypt_utils.py | 2 +- litellm/proxy/common_utils/openapi_route.py | 2 +- .../proxy/common_utils/reset_budget_job.py | 4 +- litellm/proxy/common_utils/token_count_log.py | 8 +-- litellm/proxy/control_plane/common/fanout.py | 4 +- litellm/proxy/control_plane/fleet/router.py | 2 +- litellm/proxy/db/exception_handler.py | 2 +- litellm/proxy/db/prisma_client.py | 2 +- .../guardrail_hooks/akto/akto_attachments.py | 2 +- .../custom_code/bounded_execution.py | 2 +- .../litellm_content_filter/content_filter.py | 2 +- .../guardrails/guardrail_hooks/noma/noma.py | 2 +- .../guardrail_hooks/tool_permission.py | 2 +- litellm/proxy/health_check.py | 2 +- litellm/proxy/list_api/in_memory.py | 2 +- .../common_daily_activity.py | 2 +- .../customer_endpoints.py | 2 +- .../key_management_endpoints.py | 2 +- .../customer_budget_increase_requests.py | 2 +- .../management_v1/customers.py | 2 +- .../router_settings_endpoints.py | 3 +- .../tool_management_endpoints.py | 2 +- .../user_agent_analytics_endpoints.py | 2 +- litellm/proxy/management_helpers/apps.py | 6 +- .../proxy/management_helpers/audit_logs.py | 2 +- .../management_helpers/bulk_user_creation.py | 2 +- .../customer_budget_usage.py | 2 +- .../management_helpers/customer_hierarchy.py | 2 +- litellm/proxy/management_helpers/utils.py | 4 +- .../proxy/mcp_server/faults/list_outcomes.py | 2 +- litellm/proxy/mcp_server/interactions.py | 2 +- .../proxy/mcp_server/mcp_server_manager.py | 2 +- litellm/proxy/mcp_server/result_conversion.py | 2 +- .../proxy/mcp_server/semantic_tool_filter.py | 2 +- litellm/proxy/native_compaction.py | 2 +- .../pass_through_endpoints.py | 2 +- .../pass_through_endpoints/success_handler.py | 2 +- litellm/proxy/roi_calculator/github.py | 2 +- litellm/proxy/roi_calculator/gitlab.py | 2 +- .../search_endpoints/search_tool_registry.py | 4 +- .../spend_management_endpoints.py | 4 +- litellm/proxy/utils.py | 2 +- litellm/rag/rag_query.py | 2 +- litellm/repositories/budget_repository.py | 2 +- litellm/repositories/chunked_in.py | 4 +- .../compaction_items.py | 2 +- .../tool_search_results.py | 4 +- .../transformation.py | 4 +- litellm/responses/utils.py | 4 +- litellm/router.py | 11 ++-- litellm/router_deprecated.py | 6 +- litellm/router_rust/invoke/streaming.py | 4 +- litellm/router_utils/dynamic_queue.py | 2 +- litellm/router_utils/dynamic_queue_router.py | 2 +- litellm/router_utils/endpoint_eligibility.py | 2 +- .../router_utils/kubernetes_pod_discovery.py | 8 +-- .../encrypted_content_affinity_check.py | 2 +- litellm/rust_bridge/diagnostics.py | 2 +- litellm/rust_bridge/dispatch.py | 6 +- litellm/rust_bridge/execution.py | 2 +- litellm/rust_bridge/host/routes/messages.py | 2 +- litellm/rust_bridge/public_call.py | 2 +- litellm/rust_bridge/response_metadata.py | 2 +- litellm/scripts/check_type_discipline.py | 52 +++++++++++----- litellm/scripts/pre_commit_lint.sh | 23 ++++++-- litellm/telemetry/aggregate.py | 4 +- .../types/integrations/custom_logger_v2.py | 4 +- litellm/types/rerank.py | 2 +- litellm/types/router.py | 2 +- litellm/utils.py | 4 +- litellm/vector_stores/search_query.py | 2 +- .../check_router_constructor_stub.py | 59 +++++++++++++++++++ tests/e2e/AGENTS.md | 2 +- tests/e2e/CONTRIBUTING.md | 2 +- .../test_openai_sdk_client_paths.py | 2 +- .../test_openai_sdk_client_sessions_wire.py | 2 +- tests/unit/proxy/proxy_server/conftest.py | 4 +- tests/unit/test_check_type_discipline.py | 33 +++++++++++ tests/unit/test_lint_workflow_diff_gates.py | 3 + tests/unit/test_pre_commit_lint.py | 50 +++++++++++++++- 133 files changed, 376 insertions(+), 201 deletions(-) create mode 100644 tests/code_coverage_tests/check_router_constructor_stub.py diff --git a/.github/workflows/test-linting.yml b/.github/workflows/test-linting.yml index 1802244f6ee..8ebc73bad2e 100644 --- a/.github/workflows/test-linting.yml +++ b/.github/workflows/test-linting.yml @@ -230,11 +230,11 @@ jobs: - name: Check tests/e2e basedpyright (zero errors) if: steps.changes.outputs.decision != 'skip' run: | - if git diff --name-only --diff-filter=ACMRD "$GATE_BASE_SHA" HEAD -- ':(glob)tests/e2e/**/*.py' ':(glob)tests/e2e_harness/**/*.py' pyproject.toml | grep -q .; then + if git diff --name-only --diff-filter=ACMRD "$GATE_BASE_SHA" HEAD -- ':(glob)tests/e2e/**/*.py' ':(glob)tests/e2e_harness/**/*.py' ':(glob)litellm/**/*.py' pyproject.toml uv.lock | grep -q .; then uv sync --frozen --no-install-project --group proxy-dev --group e2e-dev --extra proxy uv run --no-sync basedpyright tests/e2e tests/e2e_harness else - echo "No changed tests/e2e Python files; skipping." + echo "No changed tests/e2e or litellm Python, or dependency files; skipping." fi e2e-harness: @@ -623,6 +623,7 @@ jobs: python ./tests/code_coverage_tests/check_fastuuid_usage.py python ./tests/code_coverage_tests/check_py310_typing_imports.py python ./tests/code_coverage_tests/check_e2e_no_raw_requests.py + python ./tests/code_coverage_tests/check_router_constructor_stub.py python ./tests/code_coverage_tests/check_no_none_string_error_fields.py pytest -q --noconftest -p no:cacheprovider -c /dev/null tests/code_coverage_tests/test_check_no_none_string_error_fields.py python ./tests/code_coverage_tests/check_no_publicly_known_master_key.py diff --git a/AGENTS.md b/AGENTS.md index c99e93291e0..1c48b9ae49c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -106,7 +106,7 @@ Follow these coding conventions for new/updated code (a three-line fix in a lega - Never-nester: early returns over deep nesting - Don't throw. Model failures as values (One function (e.g., raise_public) maps error union to existing public exception contracts via exhaustive match + assert_never) - No mutation. Don't reassign variables, global or local. Instead of mutable lists and dicts, prefer tuples, frozen dataclasses (with slots=True), `MappingProxyType`, etc. - - Annotate every variable with `: Final` (LIT010). Unpacking and walrus targets cannot carry the annotation, so they are implicitly final. Don't rebind them. Never rebind or mutate function parameters (LIT011). `self`/`cls` attribute stores are the exception. If rebinding or in-place mutation is truly unavoidable, suppress with `# rebind-ok: ` + - Annotate every variable with `: Final` (LIT010). A `TypeVar`, `ParamSpec`, `TypeVarTuple`, or `TypeAliasType` is the exception and stays bare, since mypy reads a Final one as a plain variable instead of a type. Unpacking and walrus targets cannot carry the annotation, so they are implicitly final. Don't rebind them. Never rebind or mutate function parameters (LIT011). `self`/`cls` attribute stores are the exception. If rebinding or in-place mutation is truly unavoidable, suppress with `# rebind-ok: ` - Qualify every TypedDict field with `ReadOnly[...]` (LIT012), which nests freely with `Required` / `NotRequired` / `Annotated` in any order. If making the key writable is truly unavoidable, suppress with `# writable-ok: ` - Comprehensions take at most one `for` clause and one `if` clause (LIT014). Split stacked clauses into a helper generator, a named intermediate, or a plain loop. Suppress with `# comprehension-ok: ` only when unavoidable - Every pydantic model must be frozen (LIT015), set via `model_config = ConfigDict(frozen=True)`, a dict-literal `model_config`, an inner `class Config`, or the class keywords. Subclasses inherit it unless they override it. Replace in-place field writes with `model_copy(update=...)`. If making the model mutable is truly unavoidable, suppress with `# frozen-ok: ` on the `class` line diff --git a/litellm/caching/redis_batch.py b/litellm/caching/redis_batch.py index 0c4d4c18136..9241e48d3af 100644 --- a/litellm/caching/redis_batch.py +++ b/litellm/caching/redis_batch.py @@ -13,7 +13,7 @@ if TYPE_CHECKING: from litellm.rust_bridge._native import NativeRequestRedis, NativeSend _T = TypeVar("_T") -_T_co: Final = TypeVar("_T_co", covariant=True) +_T_co = TypeVar("_T_co", covariant=True) POST_CALL_FLUSH_DEADLINE_SECONDS: Final = 1.0 diff --git a/litellm/caching/redis_cluster_cache.py b/litellm/caching/redis_cluster_cache.py index 6fb84df331e..4061f1eadb6 100644 --- a/litellm/caching/redis_cluster_cache.py +++ b/litellm/caching/redis_cluster_cache.py @@ -31,7 +31,7 @@ else: Span = Any -_T: Final = TypeVar("_T") +_T = TypeVar("_T") def _connection_limit(max_connections: object) -> int | None: diff --git a/litellm/google_genai/adapters/transformation.py b/litellm/google_genai/adapters/transformation.py index 395a9685d19..b93afd5be00 100644 --- a/litellm/google_genai/adapters/transformation.py +++ b/litellm/google_genai/adapters/transformation.py @@ -150,7 +150,7 @@ _ADAPTER_DEFAULT_GENERATION_CONFIG: Final[Mapping[str, JsonValue]] = MappingProx ) _CONFIG_FIELDS: Final = TypeAdapter(Mapping[str, object]) _JSON_OBJECT_SCHEMA: Final = TypeAdapter(dict[str, JsonValue]) -_Validated: Final = TypeVar("_Validated") +_Validated = TypeVar("_Validated") _GENAI_CONTENT_PARTS: Final = TypeAdapter(Sequence[object]) _GENAI_INLINE_DATA: Final = TypeAdapter(_GenAIInlineData) _GENAI_FILE_DATA: Final = TypeAdapter(_GenAIFileData) diff --git a/litellm/integrations/anthropic_cache_control_hook.py b/litellm/integrations/anthropic_cache_control_hook.py index 262bda8589d..b12614b0260 100644 --- a/litellm/integrations/anthropic_cache_control_hook.py +++ b/litellm/integrations/anthropic_cache_control_hook.py @@ -145,7 +145,7 @@ def _validated_object_list(value: object) -> list[object] | None: return None -_MessageT: Final = TypeVar("_MessageT") +_MessageT = TypeVar("_MessageT") _CacheControlRewrite: TypeAlias = Callable[[object], ChatCompletionCachedContent | None] _MARK_CARRYING_MESSAGE_FIELDS: Final = ("content", "tool_calls") diff --git a/litellm/integrations/custom_logger_v2/call.py b/litellm/integrations/custom_logger_v2/call.py index d4c8f3c11fc..5def14dd16f 100644 --- a/litellm/integrations/custom_logger_v2/call.py +++ b/litellm/integrations/custom_logger_v2/call.py @@ -1,9 +1,9 @@ from dataclasses import dataclass -from typing import Final, Generic, TypeVar +from typing import Generic, TypeVar from litellm.integrations.custom_logger_v2.enums import Hook -StateT: Final = TypeVar("StateT") +StateT = TypeVar("StateT") @dataclass(frozen=True, slots=True) diff --git a/litellm/integrations/custom_logger_v2/dispatcher.py b/litellm/integrations/custom_logger_v2/dispatcher.py index f46058471e8..eb96f854f32 100644 --- a/litellm/integrations/custom_logger_v2/dispatcher.py +++ b/litellm/integrations/custom_logger_v2/dispatcher.py @@ -26,7 +26,7 @@ from litellm.integrations.custom_logger_v2.planner import EMPTY_PLAN, Entry, Hoo from litellm.integrations.custom_logger_v2.registry import CallbackRegistry, RegistrySnapshot from litellm.integrations.custom_logger_v2.selection import RequestSelection, is_selected -LegacyT: Final = TypeVar("LegacyT") +LegacyT = TypeVar("LegacyT") Between: TypeAlias = Callable[[Mapping[Field, object]], Awaitable[Mapping[Field, object]]] SyncBinding: TypeAlias = Callable[[object, object], object] diff --git a/litellm/integrations/custom_logger_v2/legacy.py b/litellm/integrations/custom_logger_v2/legacy.py index a849da0ec24..2b532241a53 100644 --- a/litellm/integrations/custom_logger_v2/legacy.py +++ b/litellm/integrations/custom_logger_v2/legacy.py @@ -29,7 +29,7 @@ from litellm.integrations.custom_logger_v2.patches import LiveFields from litellm.integrations.custom_logger_v2.planner import Entry, HookPlan, plan_hook from litellm.integrations.custom_logger_v2.selection import RequestSelection, Selection -ResultT: Final = TypeVar("ResultT") +ResultT = TypeVar("ResultT") SyncLegacyBinding: TypeAlias = Callable[[object, object], object] diff --git a/litellm/integrations/custom_logger_v2/logger.py b/litellm/integrations/custom_logger_v2/logger.py index ce8b9f163e0..4dabb31e797 100644 --- a/litellm/integrations/custom_logger_v2/logger.py +++ b/litellm/integrations/custom_logger_v2/logger.py @@ -8,7 +8,7 @@ from litellm.integrations.custom_logger_v2.enums import Activation, Field, Hook from litellm.integrations.custom_logger_v2.hooks import InvalidDeclarationError, Subscription from litellm.integrations.custom_logger_v2.selection import Selection -HandlerT: Final = TypeVar("HandlerT", bound=Callable[..., object]) +HandlerT = TypeVar("HandlerT", bound=Callable[..., object]) _SUBSCRIPTION_ATTR: Final = "__custom_logger_v2_subscription__" diff --git a/litellm/integrations/custom_logger_v2/manifest.py b/litellm/integrations/custom_logger_v2/manifest.py index 5984628feeb..2805da1d0df 100644 --- a/litellm/integrations/custom_logger_v2/manifest.py +++ b/litellm/integrations/custom_logger_v2/manifest.py @@ -8,7 +8,7 @@ from litellm.integrations.custom_logger_v2.hooks import InvalidDeclarationError, from litellm.integrations.custom_logger_v2.logger import CustomLoggerV2 from litellm.integrations.custom_logger_v2.selection import Selection -ResultT: Final = TypeVar("ResultT") +ResultT = TypeVar("ResultT") LegacyBinding: TypeAlias = Callable[[object, object], Awaitable[object] | None] diff --git a/litellm/integrations/lens/queries.py b/litellm/integrations/lens/queries.py index 15e9ee1f15a..fd74ac92256 100644 --- a/litellm/integrations/lens/queries.py +++ b/litellm/integrations/lens/queries.py @@ -27,8 +27,8 @@ class ClickHouseSQLEnvelope(LiteLLMBaseModel): statistics: TraceQueryStatistics -ParamsT: Final = TypeVar("ParamsT", bound=BaseModel) -RowT: Final = TypeVar("RowT") +ParamsT = TypeVar("ParamsT", bound=BaseModel) +RowT = TypeVar("RowT") class QueryResponse(LiteLLMBaseModel, Generic[RowT]): diff --git a/litellm/integrations/lens/storage.py b/litellm/integrations/lens/storage.py index 46909616222..39dffc522ba 100644 --- a/litellm/integrations/lens/storage.py +++ b/litellm/integrations/lens/storage.py @@ -24,7 +24,7 @@ _TRACE_PAGE: Final = TypeAdapter(TracePage) _TRACE: Final[TypeAdapter[Trace | None]] = TypeAdapter(Trace | None) _SPAN_DETAIL: Final[TypeAdapter[SpanDetail | None]] = TypeAdapter(SpanDetail | None) _SPAN_ERROR_PAGE: Final[TypeAdapter[SpanErrorPage | None]] = TypeAdapter(SpanErrorPage | None) -_ResponseT: Final = TypeVar("_ResponseT") +_ResponseT = TypeVar("_ResponseT") def _decode_query_response(adapter: TypeAdapter[_ResponseT], body: str) -> _ResponseT: diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py index 41263ab86e2..8dc023f7913 100644 --- a/litellm/integrations/prometheus.py +++ b/litellm/integrations/prometheus.py @@ -127,8 +127,8 @@ class _DeploymentFailureLabelValues(TypedDict): user_agent: ReadOnly[object] -_BudgetRowT: Final = TypeVar("_BudgetRowT") -_TableRowT: Final = TypeVar("_TableRowT", bound=BaseModel) +_BudgetRowT = TypeVar("_BudgetRowT") +_TableRowT = TypeVar("_TableRowT", bound=BaseModel) _DEFAULT_BUDGET_METRICS_PER_REQUEST_TIMEOUT: Final = 5.0 @@ -209,7 +209,7 @@ def _customer_budget_metrics_enabled() -> bool: return litellm.enable_end_user_cost_tracking_prometheus_only is True and not litellm.disable_end_user_cost_tracking -_MetricT: Final = TypeVar("_MetricT", bound="MetricWrapperBase") +_MetricT = TypeVar("_MetricT", bound="MetricWrapperBase") class _LabeledMetric(Generic[_MetricT]): @@ -294,7 +294,7 @@ class _LabeledMetric(Generic[_MetricT]): _MetricLike: TypeAlias = "NoOpMetric | _LabeledMetric[_MetricT] | _MetricT" -_SeriesLimitT: Final = TypeVar("_SeriesLimitT", int, float) +_SeriesLimitT = TypeVar("_SeriesLimitT", int, float) _REQUEST_METADATA_ADAPTER: Final[TypeAdapter[Mapping[str, object]]] = TypeAdapter(Mapping[str, object]) _POSITIVE_SERIES_CAP: Final[TypeAdapter[int]] = TypeAdapter(Annotated[int, Field(gt=0)]) _POSITIVE_SERIES_TTL: Final[TypeAdapter[float]] = TypeAdapter(Annotated[float, Field(gt=0)]) diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py index a6d0ca69557..419c1806b45 100644 --- a/litellm/integrations/websearch_interception/handler.py +++ b/litellm/integrations/websearch_interception/handler.py @@ -110,7 +110,7 @@ _OPTIONAL_PARAMS: Final = TypeAdapter(Mapping[str, object]) _CLAUDE_CODE_WEB_SEARCH_PROMPT_PREFIX: Final = "Perform a web search for the query:" -_ResponseT: Final = TypeVar("_ResponseT") +_ResponseT = TypeVar("_ResponseT") class _PlanMetadataView(TypedDict): diff --git a/litellm/litellm_core_utils/asyncify.py b/litellm/litellm_core_utils/asyncify.py index 17cfb3ef84f..b0b8e30009d 100644 --- a/litellm/litellm_core_utils/asyncify.py +++ b/litellm/litellm_core_utils/asyncify.py @@ -8,7 +8,7 @@ import anyio import anyio.to_thread from typing_extensions import ParamSpec, TypeVar -T_ParamSpec: Final = ParamSpec("T_ParamSpec") +T_ParamSpec = ParamSpec("T_ParamSpec") T_Retval = TypeVar("T_Retval") diff --git a/litellm/litellm_core_utils/batch_utils.py b/litellm/litellm_core_utils/batch_utils.py index bf675e6d246..6fcb2cf4a98 100644 --- a/litellm/litellm_core_utils/batch_utils.py +++ b/litellm/litellm_core_utils/batch_utils.py @@ -34,7 +34,7 @@ BATCH_COST_REQUEST_ID_SUFFIX: Final = "_batch_cost" _AZURE_PROVIDERS: Final = frozenset({LlmProviders.AZURE.value, LlmProviders.AZURE_AI.value}) _batch_create_routing: Final[ContextVar[bool]] = ContextVar("batch_create_routing", default=False) -_DeploymentT: Final = TypeVar("_DeploymentT", bound=Mapping[str, object]) +_DeploymentT = TypeVar("_DeploymentT", bound=Mapping[str, object]) class InMemoryFile(io.BytesIO): diff --git a/litellm/litellm_core_utils/chat_completion_agentic_loop.py b/litellm/litellm_core_utils/chat_completion_agentic_loop.py index 6a302aad306..828696f5a20 100644 --- a/litellm/litellm_core_utils/chat_completion_agentic_loop.py +++ b/litellm/litellm_core_utils/chat_completion_agentic_loop.py @@ -50,7 +50,7 @@ from litellm.types.utils import ( ) from litellm.utils import CustomStreamWrapper -_DispatchResult: Final = TypeVar("_DispatchResult") +_DispatchResult = TypeVar("_DispatchResult") _FOLLOWUP_INTERNAL_PARAMS: Final = frozenset( ( diff --git a/litellm/litellm_core_utils/core_helpers.py b/litellm/litellm_core_utils/core_helpers.py index f412b2dc589..812e154932a 100644 --- a/litellm/litellm_core_utils/core_helpers.py +++ b/litellm/litellm_core_utils/core_helpers.py @@ -222,7 +222,7 @@ def _http_error_status(value: object) -> int | None: return None -_Shape: Final = TypeVar("_Shape") +_Shape = TypeVar("_Shape") @dataclass(frozen=True, slots=True) diff --git a/litellm/litellm_core_utils/env_utils.py b/litellm/litellm_core_utils/env_utils.py index 462b0b3df47..82848ab6989 100644 --- a/litellm/litellm_core_utils/env_utils.py +++ b/litellm/litellm_core_utils/env_utils.py @@ -6,7 +6,7 @@ import logging import os from typing import Final, TypeVar -_NumberT: Final = TypeVar("_NumberT", int, float) +_NumberT = TypeVar("_NumberT", int, float) # Marked before logging: the LiteLLM loggers' own filters read env knobs through these helpers, so # warning first would re-enter the helper from inside the log call and recurse until RecursionError. diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py index 84a09bed68e..9cb09838757 100644 --- a/litellm/litellm_core_utils/litellm_logging.py +++ b/litellm/litellm_core_utils/litellm_logging.py @@ -708,8 +708,8 @@ _SERVED_ANTHROPIC_BODY: Final = TypeAdapter(dict[str, object]) _GOOGLE_USAGE_FIELDS: Final = frozenset(UsageMetadata.__annotations__) _REDACTED_RESULT: Final = TypeAdapter(object) _DECODED_BODY: Final = TypeAdapter(object) -_LoggedResponse: Final = TypeVar("_LoggedResponse") -_LoggedMessages: Final = TypeVar("_LoggedMessages") +_LoggedResponse = TypeVar("_LoggedResponse") +_LoggedMessages = TypeVar("_LoggedMessages") _GUARDRAIL_INFORMATION_KEY: Final = "standard_logging_guardrail_information" diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py index e43284fba14..bdb792f76d6 100644 --- a/litellm/litellm_core_utils/prompt_templates/factory.py +++ b/litellm/litellm_core_utils/prompt_templates/factory.py @@ -3190,7 +3190,7 @@ def _unsigned_thinking_identity(kind: str, thinking: object, signature: object) return None -_Replayed: Final = TypeVar("_Replayed") +_Replayed = TypeVar("_Replayed") def _with_missing_thinking_blocks( diff --git a/litellm/litellm_core_utils/prompt_templates/mid_conversation_system.py b/litellm/litellm_core_utils/prompt_templates/mid_conversation_system.py index 44860c413ab..da64d53239f 100644 --- a/litellm/litellm_core_utils/prompt_templates/mid_conversation_system.py +++ b/litellm/litellm_core_utils/prompt_templates/mid_conversation_system.py @@ -67,7 +67,7 @@ _RENDERED_ASSISTANT_PART_TYPES: Final = frozenset({"text", "server_tool_use"}) _THINKING_BLOCK_TYPES: Final = frozenset({"thinking", "redacted_thinking"}) _MessageKind: TypeAlias = Literal["system", "tool", "user", "other"] -_Message: Final = TypeVar("_Message") +_Message = TypeVar("_Message") _TextPart: TypeAlias = tuple[str, ChatCompletionCachedContent | None] diff --git a/litellm/litellm_core_utils/prompt_templates/prompt_cache_breakpoint_utils.py b/litellm/litellm_core_utils/prompt_templates/prompt_cache_breakpoint_utils.py index 25a18e84ada..854f06dca33 100644 --- a/litellm/litellm_core_utils/prompt_templates/prompt_cache_breakpoint_utils.py +++ b/litellm/litellm_core_utils/prompt_templates/prompt_cache_breakpoint_utils.py @@ -11,7 +11,7 @@ from litellm.types.llms.openai import ( PromptCacheBreakpoint, ) -_MarkedT: Final = TypeVar("_MarkedT", bound=Mapping[str, object]) +_MarkedT = TypeVar("_MarkedT", bound=Mapping[str, object]) PROMPT_CACHE_BREAKPOINT_DROP_PARAMS_HINT: Final = ( @@ -33,7 +33,7 @@ _PROMPT_CACHE_BREAKPOINT: Final = TypeAdapter(PromptCacheBreakpoint) _CHAT_COMPLETION_PROMPT_CACHE_BREAKPOINT: Final = TypeAdapter(ChatCompletionPromptCacheBreakpoint) -_AcceptedBreakpointT: Final = TypeVar("_AcceptedBreakpointT", bound=Mapping[str, object]) +_AcceptedBreakpointT = TypeVar("_AcceptedBreakpointT", bound=Mapping[str, object]) def _accepted_prompt_cache_breakpoint( diff --git a/litellm/litellm_core_utils/ptu_shares.py b/litellm/litellm_core_utils/ptu_shares.py index d56c9f2ea14..001b865d07c 100644 --- a/litellm/litellm_core_utils/ptu_shares.py +++ b/litellm/litellm_core_utils/ptu_shares.py @@ -20,7 +20,7 @@ from litellm.llms.azure.ptu_capacity import ( is_str_keyed_mapping, ) -_DeploymentT: Final = TypeVar("_DeploymentT", bound=Mapping[str, object]) +_DeploymentT = TypeVar("_DeploymentT", bound=Mapping[str, object]) WildcardRoute: TypeAlias = Callable[[str], Sequence[Mapping[str, object]]] diff --git a/litellm/litellm_core_utils/single_flight.py b/litellm/litellm_core_utils/single_flight.py index 44a84d05925..73f0db068c5 100644 --- a/litellm/litellm_core_utils/single_flight.py +++ b/litellm/litellm_core_utils/single_flight.py @@ -5,8 +5,8 @@ from dataclasses import dataclass, field from functools import lru_cache from typing import Final, Generic, ParamSpec, TypeVar -_P: Final = ParamSpec("_P") -_R: Final = TypeVar("_R") +_P = ParamSpec("_P") +_R = TypeVar("_R") @dataclass(slots=True) diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py index b69a8ba1917..1c16b137e37 100644 --- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py +++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py @@ -1354,7 +1354,7 @@ def _as_text_completion_chunk( return _text_completion_chunk_from_mapping(chunk) -_LogprobsValue: Final = TypeVar("_LogprobsValue") +_LogprobsValue = TypeVar("_LogprobsValue") def _joined_or_none(fields: Iterable[Sequence[_LogprobsValue] | None]) -> list[_LogprobsValue] | None: diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py index 44bea388649..e6312d7620d 100644 --- a/litellm/litellm_core_utils/token_counter.py +++ b/litellm/litellm_core_utils/token_counter.py @@ -617,7 +617,7 @@ def estimate_image_tokens( _MEDIA_FILE_CHARS_PER_TOKEN: Final = 4 -_EmbeddingInputT: Final = TypeVar("_EmbeddingInputT") +_EmbeddingInputT = TypeVar("_EmbeddingInputT") def _max_input_tokens(model: str) -> int | None: @@ -772,7 +772,7 @@ class _PdfReader(Protocol): EXTRAPOLATION_SAMPLES: Final = 16 -T_ParamSpec: Final = ParamSpec("T_ParamSpec") +T_ParamSpec = ParamSpec("T_ParamSpec") T_Retval = TypeVar("T_Retval") _COUNT_OFFLOAD_LIMITER: Final = anyio.lowlevel.RunVar[anyio.CapacityLimiter]("litellm_count_offload_limiter") _ANTHROPIC_TOOL_KEYS_MAPPED_BY_BRIDGE: Final = frozenset( diff --git a/litellm/litellm_core_utils/tool_fields.py b/litellm/litellm_core_utils/tool_fields.py index 7b4b9d5bf5b..53956da2581 100644 --- a/litellm/litellm_core_utils/tool_fields.py +++ b/litellm/litellm_core_utils/tool_fields.py @@ -105,8 +105,8 @@ class SentToolNames: self_named_namespace_members: Container[str] -_RenamableResponse: Final = TypeVar("_RenamableResponse", ModelResponse, ModelResponseStream) -_RenamableToolCall: Final = TypeVar( +_RenamableResponse = TypeVar("_RenamableResponse", ModelResponse, ModelResponseStream) +_RenamableToolCall = TypeVar( "_RenamableToolCall", ChatCompletionMessageToolCall | ChatCompletionMessageCustomToolCall, ChatCompletionDeltaToolCall | ChatCompletionDeltaCustomToolCall, @@ -315,7 +315,7 @@ def resolve_deployment_tool_fields( return resolve_tool_fields(kwargs, lambda: (drop_policy(kwargs),)) -_ToolT: Final = TypeVar("_ToolT") +_ToolT = TypeVar("_ToolT") HOSTED_MCP_DROP_WARNING: Final = ( "Dropping the hosted MCP tool(s) %s for model=%s on %s (drop_params=True) because this route cannot run a " @@ -430,7 +430,7 @@ def tools_without_mcp_servers( _TOOL_SELECTION_PARAMS: Final = frozenset({"tools", "tool_choice", "parallel_tool_calls"}) -_ParamsT: Final = TypeVar("_ParamsT", bound=dict[str, object]) +_ParamsT = TypeVar("_ParamsT", bound=dict[str, object]) def tool_params_without_hosted_mcp( diff --git a/litellm/llms/anthropic/messages/adapters/transformation.py b/litellm/llms/anthropic/messages/adapters/transformation.py index 2b65fb9ef1e..8919905bcf0 100644 --- a/litellm/llms/anthropic/messages/adapters/transformation.py +++ b/litellm/llms/anthropic/messages/adapters/transformation.py @@ -469,7 +469,7 @@ class AnthropicAdapter: return anthropic_wrapper.anthropic_sse_wrapper() -_BlockT: Final = TypeVar("_BlockT", bound=Mapping[str, object]) +_BlockT = TypeVar("_BlockT", bound=Mapping[str, object]) _CLAUDE_OVER_REASONING_EFFORT_PROVIDERS: Final = frozenset({LlmProviders.KYMA.value}) diff --git a/litellm/llms/anthropic/messages/context_management/editors/compact.py b/litellm/llms/anthropic/messages/context_management/editors/compact.py index cdb7c70152a..7c4b23e8d12 100644 --- a/litellm/llms/anthropic/messages/context_management/editors/compact.py +++ b/litellm/llms/anthropic/messages/context_management/editors/compact.py @@ -63,7 +63,7 @@ from ..constants import ( from ..errors import AnthropicContextManagementError from ..result import PolyfillResult -_MsgT: Final = TypeVar("_MsgT", bound=Mapping[str, object]) +_MsgT = TypeVar("_MsgT", bound=Mapping[str, object]) def _as_object(value: object) -> object: diff --git a/litellm/llms/anthropic/messages/utils.py b/litellm/llms/anthropic/messages/utils.py index 94f81eadb3b..d432cf8ffe1 100644 --- a/litellm/llms/anthropic/messages/utils.py +++ b/litellm/llms/anthropic/messages/utils.py @@ -28,7 +28,7 @@ _EFFORT_DEGRADATION_CHAIN: Final[Mapping[str, tuple[str, ...]]] = MappingProxyTy ) _THINKING_OFF: Final = "none" -_JsonValue: Final = TypeVar("_JsonValue") +_JsonValue = TypeVar("_JsonValue") def json_copy_or_original(value: _JsonValue) -> _JsonValue: diff --git a/litellm/llms/bedrock/chat/converse_to_openai.py b/litellm/llms/bedrock/chat/converse_to_openai.py index ce80a2dc8bb..bf78ef37bf5 100644 --- a/litellm/llms/bedrock/chat/converse_to_openai.py +++ b/litellm/llms/bedrock/chat/converse_to_openai.py @@ -21,7 +21,7 @@ from litellm.types.llms.openai import ( ) JsonPath: TypeAlias = tuple[str | int, ...] -_Node: Final = TypeVar("_Node") +_Node = TypeVar("_Node") _OBJECT: Final = TypeAdapter(Mapping[str, object]) _ITEMS: Final = TypeAdapter(Sequence[object]) diff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.py index 16c6bd11067..6dbe0416612 100644 --- a/litellm/llms/bedrock/chat/invoke_handler.py +++ b/litellm/llms/bedrock/chat/invoke_handler.py @@ -220,7 +220,7 @@ def _stream_decoder( return AWSEventStreamDecoder(model=model, json_mode=json_mode) -_StreamChunk: Final = TypeVar("_StreamChunk") +_StreamChunk = TypeVar("_StreamChunk") def _with_served_service_tier(chunk: _StreamChunk, served_tier: str | None) -> _StreamChunk: diff --git a/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py index 69cc8247b60..80ae38fe4b1 100644 --- a/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py +++ b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py @@ -871,7 +871,7 @@ class InvokeStreamFrame: _JSON_OBJECT: Final = TypeAdapter(Mapping[str, object]) _DECODED_JSON: Final = TypeAdapter(object) -_Frame: Final = TypeVar("_Frame", ConverseStreamFrame, InvokeStreamFrame) +_Frame = TypeVar("_Frame", ConverseStreamFrame, InvokeStreamFrame) def _event_message(raw: bytes) -> tuple[str, bytes] | None: diff --git a/litellm/llms/bedrock/passthrough/transformation.py b/litellm/llms/bedrock/passthrough/transformation.py index 646584f494c..611c454ae90 100644 --- a/litellm/llms/bedrock/passthrough/transformation.py +++ b/litellm/llms/bedrock/passthrough/transformation.py @@ -67,7 +67,7 @@ _BEDROCK_INVOKE_GUARDRAIL_HEADERS: Final = frozenset( {"x-amzn-bedrock-guardrailidentifier", "x-amzn-bedrock-guardrailversion", "x-amzn-bedrock-trace"} ) _NO_RESPONSE_HEADERS: Final[Mapping[str, str]] = MappingProxyType({}) -_TieredResponse: Final = TypeVar("_TieredResponse", bound=BaseModel) +_TieredResponse = TypeVar("_TieredResponse", bound=BaseModel) def _bedrock_endpoint_action(endpoint: str) -> str: diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py index 2cd5df6fffa..e1fa568bf35 100644 --- a/litellm/llms/custom_httpx/http_handler.py +++ b/litellm/llms/custom_httpx/http_handler.py @@ -80,7 +80,7 @@ _RequestContent: TypeAlias = str | bytes | Iterable[bytes] | AsyncIterable[bytes _IPV4_LOCAL_ADDRESS: Final = "0.0.0.0" -_HttpxTransportT: Final = TypeVar("_HttpxTransportT", httpx.BaseTransport, httpx.AsyncBaseTransport) +_HttpxTransportT = TypeVar("_HttpxTransportT", httpx.BaseTransport, httpx.AsyncBaseTransport) HTTPEventHooks: TypeAlias = Mapping[str, list[Callable[..., object]]] diff --git a/litellm/llms/minimax/videos/transformation.py b/litellm/llms/minimax/videos/transformation.py index fd014a3d521..e9c0e67c2b5 100644 --- a/litellm/llms/minimax/videos/transformation.py +++ b/litellm/llms/minimax/videos/transformation.py @@ -177,7 +177,7 @@ _CREATE_REQUEST_PARAMS: Final = frozenset({*_CREATE_BODY_KEYS, "content", "input _TASK_NOT_FOUND_MESSAGE: Final = "record not found" -_ParsedT: Final = TypeVar("_ParsedT") +_ParsedT = TypeVar("_ParsedT") def _minimax_error(status_code: int, message: str) -> MinimaxVideoError: diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.py index f6968966543..9c9cf957e6a 100644 --- a/litellm/llms/openai/responses/guardrail_translation/handler.py +++ b/litellm/llms/openai/responses/guardrail_translation/handler.py @@ -574,7 +574,7 @@ def _rewritten_tool_search_call(item: object, payload: str | None) -> object: return item -_RewriteKey: Final = TypeVar("_RewriteKey") +_RewriteKey = TypeVar("_RewriteKey") def _delta_replacements(rewrites: Mapping[_RewriteKey, str]) -> Mapping[_RewriteKey, Iterator[str]]: @@ -1053,7 +1053,7 @@ def tool_output_texts(item: object) -> tuple[tuple[int | None, str], ...]: return ((None, tool_content),) if isinstance(tool_content, str) and tool_content else () -_Grouped: Final = TypeVar("_Grouped") +_Grouped = TypeVar("_Grouped") def _pair_call_id(pair: tuple[str, object]) -> str: diff --git a/litellm/llms/openai_like/common_utils.py b/litellm/llms/openai_like/common_utils.py index dcfed3f058f..04a5cb8fe7d 100644 --- a/litellm/llms/openai_like/common_utils.py +++ b/litellm/llms/openai_like/common_utils.py @@ -60,7 +60,7 @@ class OpenAILikeBase: return api_base, headers -_HeaderValue: Final = TypeVar("_HeaderValue") +_HeaderValue = TypeVar("_HeaderValue") def with_canonical_authorization( diff --git a/litellm/llms/vercel_ai_gateway/decisions/transformation.py b/litellm/llms/vercel_ai_gateway/decisions/transformation.py index c42283efd7b..5525cfa0403 100644 --- a/litellm/llms/vercel_ai_gateway/decisions/transformation.py +++ b/litellm/llms/vercel_ai_gateway/decisions/transformation.py @@ -14,7 +14,7 @@ from litellm.types.decisions import ( OpenAIDecisionInputTokensDetails, ) -_Model: Final = TypeVar("_Model", bound=BaseModel) +_Model = TypeVar("_Model", bound=BaseModel) class _ProviderAttempt(BaseModel): diff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.py index b606bddcf4d..0e2e56db601 100644 --- a/litellm/llms/vertex_ai/common_utils.py +++ b/litellm/llms/vertex_ai/common_utils.py @@ -809,7 +809,7 @@ def _integer_enums_fit(schema: JsonValue) -> bool: return enums_fit(schema) or not any(map(_is_integer_enum, _json_nodes(schema))) -_GeminiRequestPart: Final = TypeVar("_GeminiRequestPart") +_GeminiRequestPart = TypeVar("_GeminiRequestPart") def with_integer_enums_that_fit( diff --git a/litellm/llms/vertex_ai/context_caching/rejected_cache_retry.py b/litellm/llms/vertex_ai/context_caching/rejected_cache_retry.py index 7334fb0520a..1179c47143d 100644 --- a/litellm/llms/vertex_ai/context_caching/rejected_cache_retry.py +++ b/litellm/llms/vertex_ai/context_caching/rejected_cache_retry.py @@ -13,8 +13,8 @@ from litellm.utils import is_cached_message from .known_cached_contents import names_rejected_cache -Built: Final = TypeVar("Built") -Sent: Final = TypeVar("Sent") +Built = TypeVar("Built") +Sent = TypeVar("Sent") def _build_from_copies( diff --git a/litellm/llms/vertex_ai/gemini/long_decode.py b/litellm/llms/vertex_ai/gemini/long_decode.py index 25aae70a853..5b887f4b3a2 100644 --- a/litellm/llms/vertex_ai/gemini/long_decode.py +++ b/litellm/llms/vertex_ai/gemini/long_decode.py @@ -63,7 +63,7 @@ _CANDIDATE_COUNT_KEYS: Final = ("candidate_count", "candidateCount") LongDecodeHops: TypeAlias = tuple[GenerateContentResponseBody, ...] AsyncHopPost: TypeAlias = Callable[[RequestBody], Awaitable[httpx.Response]] SyncHopPost: TypeAlias = Callable[[RequestBody], httpx.Response] -_Metadata: Final = TypeVar("_Metadata", bound=Mapping[str, object]) +_Metadata = TypeVar("_Metadata", bound=Mapping[str, object]) @dataclass(frozen=True, slots=True) diff --git a/litellm/llms/vertex_ai/gemini/rejected_thought_signature_retry.py b/litellm/llms/vertex_ai/gemini/rejected_thought_signature_retry.py index 32893471c11..01ada902fe9 100644 --- a/litellm/llms/vertex_ai/gemini/rejected_thought_signature_retry.py +++ b/litellm/llms/vertex_ai/gemini/rejected_thought_signature_retry.py @@ -11,8 +11,8 @@ from litellm.types.llms.vertex_ai import ContentType, PartType, RequestBody from ..context_caching.rejected_cache_retry import status_and_message -Body: Final = TypeVar("Body", bound=Mapping[str, object]) -Sent: Final = TypeVar("Sent") +Body = TypeVar("Body", bound=Mapping[str, object]) +Sent = TypeVar("Sent") _REJECTED_SIGNATURE_MARKER: Final = "thought signature" _SIGNATURE_KEYS: Final = frozenset({"thoughtSignature", "thought_signature"}) diff --git a/litellm/llms/vertex_ai/request_labels.py b/litellm/llms/vertex_ai/request_labels.py index 7186f523c92..72c1216afdb 100644 --- a/litellm/llms/vertex_ai/request_labels.py +++ b/litellm/llms/vertex_ai/request_labels.py @@ -33,7 +33,7 @@ _ANY_MAPPING: Final = TypeAdapter(Mapping[object, object]) _ANY_SEQUENCE: Final = TypeAdapter(tuple[object, ...]) Label: TypeAlias = tuple[str, str] -_HeaderValue: Final = TypeVar("_HeaderValue") +_HeaderValue = TypeVar("_HeaderValue") def vertex_request_label_fields() -> tuple[str, ...]: diff --git a/litellm/llms/volcengine/videos/transformation.py b/litellm/llms/volcengine/videos/transformation.py index ca4d3546636..c5cea9c2378 100644 --- a/litellm/llms/volcengine/videos/transformation.py +++ b/litellm/llms/volcengine/videos/transformation.py @@ -37,7 +37,7 @@ if TYPE_CHECKING: from litellm.litellm_core_utils.litellm_logging import Logging -_ParsedT: Final = TypeVar("_ParsedT") +_ParsedT = TypeVar("_ParsedT") class VolcEngineVideoError(BaseLLMException): diff --git a/litellm/proxy/auth/model_checks.py b/litellm/proxy/auth/model_checks.py index ed04ccfa381..735795397f2 100644 --- a/litellm/proxy/auth/model_checks.py +++ b/litellm/proxy/auth/model_checks.py @@ -108,7 +108,7 @@ _PROVIDERS_LISTED_ONLY_THROUGH_A_DEPLOYMENT: Final = frozenset( {LlmProviders.OPENROUTER.value, LlmProviders.HOSTED_VLLM.value, LlmProviders.LITELLM_PROXY.value} ) -_Listed: Final = TypeVar("_Listed") +_Listed = TypeVar("_Listed") async def run_model_listing(listing: Callable[[], _Listed]) -> _Listed: diff --git a/litellm/proxy/bug_report_config.py b/litellm/proxy/bug_report_config.py index 6c0209644b4..019de5ade3e 100644 --- a/litellm/proxy/bug_report_config.py +++ b/litellm/proxy/bug_report_config.py @@ -108,7 +108,7 @@ def _litellm_settings_keys() -> frozenset[str]: def _router_settings_keys() -> frozenset[str]: from litellm.router import Router - return frozenset(name for name in inspect.signature(Router.__init__).parameters if name != "self") # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType] # untyped params, only names are read + return frozenset(inspect.signature(Router).parameters) @functools.cache diff --git a/litellm/proxy/client/cli/commands/agents.py b/litellm/proxy/client/cli/commands/agents.py index d6381f01ea1..7ba52cfda7b 100644 --- a/litellm/proxy/client/cli/commands/agents.py +++ b/litellm/proxy/client/cli/commands/agents.py @@ -629,8 +629,8 @@ class ConfiguredModelInfo: _UNCONFIGURED: Final = ConfiguredModelInfo() _NO_CONFIGURED: Final[Mapping[str, ConfiguredModelInfo]] = MappingProxyType({}) _ALL_PROXY_MODELS: Final = "all-proxy-models" -_Pinned: Final = TypeVar("_Pinned", bound=Hashable) -_Fetched: Final = TypeVar("_Fetched", bound=LiteLLMBaseModel) +_Pinned = TypeVar("_Pinned", bound=Hashable) +_Fetched = TypeVar("_Fetched", bound=LiteLLMBaseModel) def _public_name(deployment: _Deployment) -> str: @@ -1437,7 +1437,7 @@ def _launch( raise click.ClickException(str(e)) -_Decorated: Final = TypeVar("_Decorated", bound=Callable[..., object] | click.Command) +_Decorated = TypeVar("_Decorated", bound=Callable[..., object] | click.Command) def _subscription_option(binary: str) -> Callable[[_Decorated], _Decorated]: diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.py index 01642ba34a3..d58ded9da80 100644 --- a/litellm/proxy/client/cli/commands/auth.py +++ b/litellm/proxy/client/cli/commands/auth.py @@ -146,7 +146,7 @@ class CliAuthResult(TypedDict): team_id: str | None -_TeamMapping: Final = TypeVar("_TeamMapping", bound=Mapping[str, object]) +_TeamMapping = TypeVar("_TeamMapping", bound=Mapping[str, object]) _JSON_OBJECT: Final = TypeAdapter(Mapping[str, object], config=ConfigDict(hide_input_in_errors=True)) _DECODED_JSON: Final = TypeAdapter(object) diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py index 1c5ad57fd06..bd37d66d34e 100644 --- a/litellm/proxy/common_request_processing.py +++ b/litellm/proxy/common_request_processing.py @@ -220,9 +220,9 @@ from litellm.types.router_weights import RouterWeights, validate_router_weights _LateResponseT = TypeVar("_LateResponseT") _LlmCallT = TypeVar("_LlmCallT") -_ResponseT: Final = TypeVar("_ResponseT") -_ChunkT: Final = TypeVar("_ChunkT") -_ProcessedT: Final = TypeVar("_ProcessedT") +_ResponseT = TypeVar("_ResponseT") +_ChunkT = TypeVar("_ChunkT") +_ProcessedT = TypeVar("_ProcessedT") KNOWN_PROXY_ROUTES: Final = frozenset( route for member in LiteLLMRoutes for route in member.value if route.startswith("/") diff --git a/litellm/proxy/common_utils/codex_catalog_source.py b/litellm/proxy/common_utils/codex_catalog_source.py index 994ffe8e72e..c36b7b0da22 100644 --- a/litellm/proxy/common_utils/codex_catalog_source.py +++ b/litellm/proxy/common_utils/codex_catalog_source.py @@ -50,7 +50,7 @@ class CodexStock: instructions: str -_Value: Final = TypeVar("_Value") +_Value = TypeVar("_Value") class CodexReleaseClient(Protocol): diff --git a/litellm/proxy/common_utils/encrypt_decrypt_utils.py b/litellm/proxy/common_utils/encrypt_decrypt_utils.py index 4cb04656ede..6d1e0cb7c97 100644 --- a/litellm/proxy/common_utils/encrypt_decrypt_utils.py +++ b/litellm/proxy/common_utils/encrypt_decrypt_utils.py @@ -299,7 +299,7 @@ def decrypt_bearer_token(token: str, prefix: str) -> str | None: return None -_Passthrough: Final = TypeVar("_Passthrough") +_Passthrough = TypeVar("_Passthrough") @overload diff --git a/litellm/proxy/common_utils/openapi_route.py b/litellm/proxy/common_utils/openapi_route.py index 69fbeb67277..761b221f732 100644 --- a/litellm/proxy/common_utils/openapi_route.py +++ b/litellm/proxy/common_utils/openapi_route.py @@ -12,7 +12,7 @@ from starlette.routing import BaseRoute, Route from litellm.proxy.common_utils.custom_openapi_spec import JsonObject OpenAPISchema: TypeAlias = JsonObject -Inputs: Final = TypeVar("Inputs") +Inputs = TypeVar("Inputs") _SERVERS: Final = TypeAdapter(list[dict[str, object]]) diff --git a/litellm/proxy/common_utils/reset_budget_job.py b/litellm/proxy/common_utils/reset_budget_job.py index 7653b5a1569..af55ff47c6e 100644 --- a/litellm/proxy/common_utils/reset_budget_job.py +++ b/litellm/proxy/common_utils/reset_budget_job.py @@ -164,8 +164,8 @@ class _CustomerMemberRow(_CustomerScopedRow, Protocol): _RowT = TypeVar("_RowT") -_RowT_co: Final = TypeVar("_RowT_co", covariant=True) -_CustomerRowT: Final = TypeVar("_CustomerRowT", bound=_CustomerScopedRow) +_RowT_co = TypeVar("_RowT_co", covariant=True) +_CustomerRowT = TypeVar("_CustomerRowT", bound=_CustomerScopedRow) class CustomerScopeTable(Protocol[_RowT_co]): diff --git a/litellm/proxy/common_utils/token_count_log.py b/litellm/proxy/common_utils/token_count_log.py index 83520ef1ade..4301ec05ef9 100644 --- a/litellm/proxy/common_utils/token_count_log.py +++ b/litellm/proxy/common_utils/token_count_log.py @@ -31,10 +31,10 @@ def _logfmt_value(value: str | None) -> str: return json.dumps(value).translate(_JSON_ESCAPED_BRACES) -_Counted: Final = TypeVar("_Counted") -_Rejection: Final = TypeVar("_Rejection") -_ProviderCount: Final = TypeVar("_ProviderCount", bound=Mapping[str, object]) -_Answer: Final = TypeVar("_Answer") +_Counted = TypeVar("_Counted") +_Rejection = TypeVar("_Rejection") +_ProviderCount = TypeVar("_ProviderCount", bound=Mapping[str, object]) +_Answer = TypeVar("_Answer") @dataclass(frozen=True, slots=True) diff --git a/litellm/proxy/control_plane/common/fanout.py b/litellm/proxy/control_plane/common/fanout.py index dc527dd78dd..1f669e6223f 100644 --- a/litellm/proxy/control_plane/common/fanout.py +++ b/litellm/proxy/control_plane/common/fanout.py @@ -16,8 +16,8 @@ from litellm.proxy.control_plane.dataplanes.client import ( from litellm.proxy.control_plane.dataplanes.credentials import CredentialUnavailable from litellm.proxy.control_plane.dataplanes.registry import Dataplane -T: Final = TypeVar("T") -M: Final = TypeVar("M") +T = TypeVar("T") +M = TypeVar("M") @dataclass(frozen=True, slots=True) diff --git a/litellm/proxy/control_plane/fleet/router.py b/litellm/proxy/control_plane/fleet/router.py index 4a5642a7212..94171c94783 100644 --- a/litellm/proxy/control_plane/fleet/router.py +++ b/litellm/proxy/control_plane/fleet/router.py @@ -19,7 +19,7 @@ from litellm.proxy.control_plane.fleet.service import fetch_models, fetch_teams, from litellm.types.proxy.control_plane.dataplanes import UnreachableDataplane from litellm.types.proxy.control_plane.fleet import FleetModel, FleetModelsResponse, FleetTeam, FleetTeamsResponse -T: Final = TypeVar("T") +T = TypeVar("T") router: Final = APIRouter(prefix="/fleet", tags=["fleet"]) diff --git a/litellm/proxy/db/exception_handler.py b/litellm/proxy/db/exception_handler.py index cdafa2cf52f..2714e188a9f 100644 --- a/litellm/proxy/db/exception_handler.py +++ b/litellm/proxy/db/exception_handler.py @@ -628,7 +628,7 @@ def _coerce_timeout(value: object, fallback: float) -> float: return fallback -_ReadResultT: Final = TypeVar("_ReadResultT") +_ReadResultT = TypeVar("_ReadResultT") class _DBReconnectClient(Protocol): diff --git a/litellm/proxy/db/prisma_client.py b/litellm/proxy/db/prisma_client.py index f90a9f72bf4..4653569e74c 100644 --- a/litellm/proxy/db/prisma_client.py +++ b/litellm/proxy/db/prisma_client.py @@ -275,7 +275,7 @@ class _PrismaDrainTracker: await self._drained.wait() -_EngineResponseT: Final = TypeVar("_EngineResponseT") +_EngineResponseT = TypeVar("_EngineResponseT") class _TrackedPrismaEngine: diff --git a/litellm/proxy/guardrails/guardrail_hooks/akto/akto_attachments.py b/litellm/proxy/guardrails/guardrail_hooks/akto/akto_attachments.py index 54d09ff0b1e..c72f31fdf8d 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/akto/akto_attachments.py +++ b/litellm/proxy/guardrails/guardrail_hooks/akto/akto_attachments.py @@ -42,7 +42,7 @@ _FILE_SOURCE_FIELDS: Final = frozenset(("file_data", "file_id")) _ATTACHMENT_BLOCK_TYPES: Final = frozenset(_FILE_CHECKED_FIELDS) _OBJECT_MAPPING: Final[TypeAdapter[dict[str, object]]] = TypeAdapter(dict[str, object]) -_T: Final = TypeVar("_T") +_T = TypeVar("_T") @dataclass(frozen=True, slots=True) diff --git a/litellm/proxy/guardrails/guardrail_hooks/custom_code/bounded_execution.py b/litellm/proxy/guardrails/guardrail_hooks/custom_code/bounded_execution.py index d926b40da6a..eaf17d2751c 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/custom_code/bounded_execution.py +++ b/litellm/proxy/guardrails/guardrail_hooks/custom_code/bounded_execution.py @@ -22,7 +22,7 @@ from typing import Final, Generic, TypeVar from litellm._logging import verbose_proxy_logger -T: Final = TypeVar("T") +T = TypeVar("T") _INTERRUPT_GRACE_SECONDS: Final = 1.0 _INTERRUPT_POLL_SECONDS: Final = 0.05 diff --git a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py index c994058dd6c..3e340d92fd9 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py +++ b/litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py @@ -85,7 +85,7 @@ from .patterns import PATTERN_EXTRA_CONFIG, PATTERN_STREAMING_HOLDBACK_CHARS, ge MAX_KEYWORD_VALUE_GAP_WORDS: Final = 1 _DECODED_ARGUMENTS: Final = TypeAdapter(object) -_StreamItemT: Final = TypeVar("_StreamItemT") +_StreamItemT = TypeVar("_StreamItemT") _JSON_ENTRIES: Final = TypeAdapter(list[object]) GAP_WORD_TOKENIZER: Final = re.compile(r"\b\w+\b") SENTENCE_TERMINATORS: Final = re.compile(r"[.!?]+") diff --git a/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py b/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py index 8e6bc6ef4b4..e36ec7b9997 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py +++ b/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py @@ -54,7 +54,7 @@ SENSITIVE_DATA_DETECTOR_KEYS: Final[list[str]] = ["sensitiveData", "dataDetector # Type aliases MessageRole = Literal["user", "assistant"] LLMResponse = object -_LLMResponseT: Final = TypeVar("_LLMResponseT") +_LLMResponseT = TypeVar("_LLMResponseT") _LEGACY_NOMA_DEPRECATION_WARNED = False _DECODED_JSON: Final = TypeAdapter(object) diff --git a/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py b/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py index 09f92f9c8ee..d0875bfe76f 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py +++ b/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py @@ -80,7 +80,7 @@ _DECODED_ARGUMENTS: Final = TypeAdapter(object) _REQUEST_DATA: Final = TypeAdapter(object) _ToolTarget: TypeAlias = tuple[str | None, str | None] _JudgedCalls: TypeAlias = Mapping[str, tuple[tuple[str, str], ...]] -_GroupedT: Final = TypeVar("_GroupedT") +_GroupedT = TypeVar("_GroupedT") def _snake_case(name: str) -> str: diff --git a/litellm/proxy/health_check.py b/litellm/proxy/health_check.py index 0f5f5132c1f..32c522d19a7 100644 --- a/litellm/proxy/health_check.py +++ b/litellm/proxy/health_check.py @@ -21,7 +21,7 @@ if TYPE_CHECKING: from litellm.router import Router logger: Final = logging.getLogger(__name__) -_DeploymentT: Final = TypeVar("_DeploymentT", bound=Mapping[str, object]) +_DeploymentT = TypeVar("_DeploymentT", bound=Mapping[str, object]) from litellm.constants import ( BACKGROUND_HEALTH_CHECK_MAX_TOKENS, BACKGROUND_HEALTH_CHECK_MAX_TOKENS_REASONING, diff --git a/litellm/proxy/list_api/in_memory.py b/litellm/proxy/list_api/in_memory.py index 3f3f173ba1a..dad938b1c9f 100644 --- a/litellm/proxy/list_api/in_memory.py +++ b/litellm/proxy/list_api/in_memory.py @@ -25,7 +25,7 @@ from litellm.proxy.list_api.list_framework import ( Within, ) -TRow: Final = TypeVar("TRow") +TRow = TypeVar("TRow") Cell: TypeAlias = str | int | float | datetime | None # A tuple-valued cell is a row's repeated field (a model group's providers, say). A predicate diff --git a/litellm/proxy/management_endpoints/common_daily_activity.py b/litellm/proxy/management_endpoints/common_daily_activity.py index 64b4794287a..44586263efa 100644 --- a/litellm/proxy/management_endpoints/common_daily_activity.py +++ b/litellm/proxy/management_endpoints/common_daily_activity.py @@ -58,7 +58,7 @@ from litellm.types.repositories.daily_activity import ( SpendLogsWindow, ) -_T: Final = TypeVar("_T") +_T = TypeVar("_T") @dataclass(frozen=True, slots=True) diff --git a/litellm/proxy/management_endpoints/customer_endpoints.py b/litellm/proxy/management_endpoints/customer_endpoints.py index 3ce5a33adfd..5c7aa577973 100644 --- a/litellm/proxy/management_endpoints/customer_endpoints.py +++ b/litellm/proxy/management_endpoints/customer_endpoints.py @@ -55,7 +55,7 @@ from litellm.types.proxy.management_endpoints.customer_endpoints import ( UnblockUsersResponse, ) -_RowT_co: Final = TypeVar("_RowT_co", covariant=True) +_RowT_co = TypeVar("_RowT_co", covariant=True) _STR_OBJECT_DICT: Final = TypeAdapter(dict[str, object]) _CLEARABLE_LIST_FIELDS: Final = frozenset({"models"}) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index a42e54ec006..5b46be6d0d2 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -1069,7 +1069,7 @@ _KEY_TYPE_PRESET_ROUTES: Final = MappingProxyType( ) -_KeyJsonT: Final = TypeVar("_KeyJsonT", bound=dict[str, object]) +_KeyJsonT = TypeVar("_KeyJsonT", bound=dict[str, object]) def handle_key_type(data: GenerateKeyRequest, data_json: _KeyJsonT) -> _KeyJsonT: diff --git a/litellm/proxy/management_endpoints/management_v1/customer_budget_increase_requests.py b/litellm/proxy/management_endpoints/management_v1/customer_budget_increase_requests.py index 0b04c45844c..66c910925d4 100644 --- a/litellm/proxy/management_endpoints/management_v1/customer_budget_increase_requests.py +++ b/litellm/proxy/management_endpoints/management_v1/customer_budget_increase_requests.py @@ -56,7 +56,7 @@ Caller: TypeAlias = Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)] Admin: TypeAlias = Annotated[str, Depends(customer_actor)] Cache: TypeAlias = Annotated[UserApiKeyCache, Depends(get_user_api_key_cache)] -T: Final = TypeVar("T") +T = TypeVar("T") _REQUEST: Final = TypeAdapter(BudgetIncreaseRequest) _REQUESTS: Final = TypeAdapter(tuple[BudgetIncreaseRequest, ...]) diff --git a/litellm/proxy/management_endpoints/management_v1/customers.py b/litellm/proxy/management_endpoints/management_v1/customers.py index 1413cbf0a9b..f60f81d0f76 100644 --- a/litellm/proxy/management_endpoints/management_v1/customers.py +++ b/litellm/proxy/management_endpoints/management_v1/customers.py @@ -50,7 +50,7 @@ from litellm.types.proxy.management_endpoints.customer_hierarchy import ( ) from litellm.types.proxy.management_endpoints.management_v1 import ListMeta, ListResponse, ProblemDetail -T: Final = TypeVar("T") +T = TypeVar("T") _ERROR_DETAILS: Final[Mapping[ErrorCode, tuple[int, str, str]]] = MappingProxyType( diff --git a/litellm/proxy/management_endpoints/router_settings_endpoints.py b/litellm/proxy/management_endpoints/router_settings_endpoints.py index cbb7d53073b..0ede61b090b 100644 --- a/litellm/proxy/management_endpoints/router_settings_endpoints.py +++ b/litellm/proxy/management_endpoints/router_settings_endpoints.py @@ -74,9 +74,8 @@ def _parameter_annotation(parameter: _AnnotatedParameter) -> object: def _get_routing_strategies_from_router_class() -> list[str]: """ - Dynamically extract routing strategies from the Router class __init__ method. + Dynamically extract routing strategies from the Router constructor's signature. """ - # Get the __init__ signature sig: Final = inspect.signature(Router) # Get the routing_strategy parameter diff --git a/litellm/proxy/management_endpoints/tool_management_endpoints.py b/litellm/proxy/management_endpoints/tool_management_endpoints.py index a2c199d886c..7835a916bf0 100644 --- a/litellm/proxy/management_endpoints/tool_management_endpoints.py +++ b/litellm/proxy/management_endpoints/tool_management_endpoints.py @@ -59,7 +59,7 @@ from litellm.types.tool_management import ( ToolUsageLogsResponse, ) -_RowT_co: Final = TypeVar("_RowT_co", covariant=True) +_RowT_co = TypeVar("_RowT_co", covariant=True) if TYPE_CHECKING: diff --git a/litellm/proxy/management_endpoints/user_agent_analytics_endpoints.py b/litellm/proxy/management_endpoints/user_agent_analytics_endpoints.py index c5016b49487..b4d863672c0 100644 --- a/litellm/proxy/management_endpoints/user_agent_analytics_endpoints.py +++ b/litellm/proxy/management_endpoints/user_agent_analytics_endpoints.py @@ -139,7 +139,7 @@ _DISTINCT_TAG_ROWS: Final = TypeAdapter(list[_DistinctTagRow]) _ACTIVE_USERS_ROWS: Final = TypeAdapter(list[_ActiveUsersRow]) _TAG_SUMMARY_ROWS: Final = TypeAdapter(list[_TagSummaryRow]) -_RowT_co: Final = TypeVar("_RowT_co", covariant=True) +_RowT_co = TypeVar("_RowT_co", covariant=True) if TYPE_CHECKING: diff --git a/litellm/proxy/management_helpers/apps.py b/litellm/proxy/management_helpers/apps.py index da28815fbd0..e369bbb0fcc 100644 --- a/litellm/proxy/management_helpers/apps.py +++ b/litellm/proxy/management_helpers/apps.py @@ -104,9 +104,9 @@ class _SharedProfiles(BaseModel): _DEFINITION_PARAM: Final = "customer_app_definition" _DEFINITION: Final = AuthObject.customer_app_definition() _PARENT_ORG_ID: Final = TypeAdapter(str) -AppEntity: Final = TypeVar("AppEntity", App, AppOrganization, AppMember, AppGroup, AppGroupOrganization) -AppAssociation: Final = TypeVar("AppAssociation", AppOrganization, AppMember) -CachedModel: Final = TypeVar("CachedModel", bound=BaseModel) +AppEntity = TypeVar("AppEntity", App, AppOrganization, AppMember, AppGroup, AppGroupOrganization) +AppAssociation = TypeVar("AppAssociation", AppOrganization, AppMember) +CachedModel = TypeVar("CachedModel", bound=BaseModel) class AppRepository(PrismaTableRepository[PrismaRecord]): diff --git a/litellm/proxy/management_helpers/audit_logs.py b/litellm/proxy/management_helpers/audit_logs.py index f3e7f26e628..be2c2c91c20 100644 --- a/litellm/proxy/management_helpers/audit_logs.py +++ b/litellm/proxy/management_helpers/audit_logs.py @@ -167,7 +167,7 @@ def _audit_log_task_done_callback(task: asyncio.Task) -> None: verbose_proxy_logger.error("Audit log callback task failed: %s", exc, exc_info=exc) -_T: Final = TypeVar("_T") +_T = TypeVar("_T") class AuditTaskRegistry: diff --git a/litellm/proxy/management_helpers/bulk_user_creation.py b/litellm/proxy/management_helpers/bulk_user_creation.py index 5a68a9a2826..a91c0488763 100644 --- a/litellm/proxy/management_helpers/bulk_user_creation.py +++ b/litellm/proxy/management_helpers/bulk_user_creation.py @@ -84,7 +84,7 @@ BULK_NEW_USER_CONCURRENCY: Final = 10 TeamRole: TypeAlias = Literal["user", "admin"] KeyGenerator: TypeAlias = Callable[..., Awaitable[object]] -_T: Final = TypeVar("_T") +_T = TypeVar("_T") @dataclass(frozen=True, slots=True) diff --git a/litellm/proxy/management_helpers/customer_budget_usage.py b/litellm/proxy/management_helpers/customer_budget_usage.py index ac3b2f2685a..215cf0cf0ab 100644 --- a/litellm/proxy/management_helpers/customer_budget_usage.py +++ b/litellm/proxy/management_helpers/customer_budget_usage.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: from litellm.proxy.spend_tracking.budget_reservation import BudgetCounter -Entity: Final = TypeVar("Entity", Organization, Team, CustomerMember) +Entity = TypeVar("Entity", Organization, Team, CustomerMember) def _identity(entity: Organization | Team | CustomerMember) -> tuple[CustomerScopeKey, str, Budget | None]: diff --git a/litellm/proxy/management_helpers/customer_hierarchy.py b/litellm/proxy/management_helpers/customer_hierarchy.py index 4a56b6815e3..ef3ba9028b6 100644 --- a/litellm/proxy/management_helpers/customer_hierarchy.py +++ b/litellm/proxy/management_helpers/customer_hierarchy.py @@ -200,7 +200,7 @@ class TransactionSource(Protocol): def tx(self) -> AbstractAsyncContextManager["Prisma"]: ... -T: Final = TypeVar("T") +T = TypeVar("T") @dataclass(frozen=True, slots=True) diff --git a/litellm/proxy/management_helpers/utils.py b/litellm/proxy/management_helpers/utils.py index a7bf1fe7790..f3888ffef8c 100644 --- a/litellm/proxy/management_helpers/utils.py +++ b/litellm/proxy/management_helpers/utils.py @@ -931,8 +931,8 @@ async def _emit_management_endpoint_otel_span( ) -_P: Final = ParamSpec("_P") -_R: Final = TypeVar("_R") +_P = ParamSpec("_P") +_R = TypeVar("_R") def management_endpoint_wrapper(func: Callable[_P, Awaitable[_R]]) -> Callable[_P, Awaitable[_R]]: diff --git a/litellm/proxy/mcp_server/faults/list_outcomes.py b/litellm/proxy/mcp_server/faults/list_outcomes.py index b8af3ead8fb..ef7144f14ac 100644 --- a/litellm/proxy/mcp_server/faults/list_outcomes.py +++ b/litellm/proxy/mcp_server/faults/list_outcomes.py @@ -258,7 +258,7 @@ def rate_limit_retry_delay( return min(max_delay, base_delay * 2.0**attempt * (1 + jitter)) -T: Final = TypeVar("T") +T = TypeVar("T") async def retry_upstream_rate_limit( diff --git a/litellm/proxy/mcp_server/interactions.py b/litellm/proxy/mcp_server/interactions.py index 24cedb57ef8..232a2929673 100644 --- a/litellm/proxy/mcp_server/interactions.py +++ b/litellm/proxy/mcp_server/interactions.py @@ -193,7 +193,7 @@ def seal_continuation( return InputRequiredResult(input_requests=result.input_requests, request_state=sealed.ok, _meta=result.meta) -_Terminal: Final = TypeVar("_Terminal") +_Terminal = TypeVar("_Terminal") @dataclass(frozen=True, slots=True) diff --git a/litellm/proxy/mcp_server/mcp_server_manager.py b/litellm/proxy/mcp_server/mcp_server_manager.py index 2e65c51fdba..6c4dcab2f28 100644 --- a/litellm/proxy/mcp_server/mcp_server_manager.py +++ b/litellm/proxy/mcp_server/mcp_server_manager.py @@ -2006,7 +2006,7 @@ class _InternalNetworkSettings(Protocol): def get(self, key: Literal["mcp_internal_ip_ranges"], /) -> list[str] | None: ... -_Gathered: Final = TypeVar("_Gathered") +_Gathered = TypeVar("_Gathered") async def _gather_before_relaying_url_elicitation(tasks: Sequence[asyncio.Task[_Gathered]]) -> Sequence[_Gathered]: diff --git a/litellm/proxy/mcp_server/result_conversion.py b/litellm/proxy/mcp_server/result_conversion.py index f48f853aa52..66e6f2cbeee 100644 --- a/litellm/proxy/mcp_server/result_conversion.py +++ b/litellm/proxy/mcp_server/result_conversion.py @@ -80,7 +80,7 @@ def is_url_elicitation_required(exc: BaseException) -> bool: return isinstance(exc, MCPError) and exc.error.code == URL_ELICITATION_REQUIRED -_ToolResult: Final = TypeVar("_ToolResult") +_ToolResult = TypeVar("_ToolResult") async def url_elicitation_as_error_result(execution: Awaitable[_ToolResult]) -> _ToolResult | CallToolResult: diff --git a/litellm/proxy/mcp_server/semantic_tool_filter.py b/litellm/proxy/mcp_server/semantic_tool_filter.py index 8666c05079d..1c89acac01f 100644 --- a/litellm/proxy/mcp_server/semantic_tool_filter.py +++ b/litellm/proxy/mcp_server/semantic_tool_filter.py @@ -21,7 +21,7 @@ if TYPE_CHECKING: from litellm.router import Router -_Tool: Final = TypeVar("_Tool") +_Tool = TypeVar("_Tool") class SemanticToolFilterContextWindowError(Exception): diff --git a/litellm/proxy/native_compaction.py b/litellm/proxy/native_compaction.py index fd27e7fbbdc..98cbe528321 100644 --- a/litellm/proxy/native_compaction.py +++ b/litellm/proxy/native_compaction.py @@ -20,7 +20,7 @@ from litellm.router_strategy.complexity_router.context_compaction import ( native_compaction_call, ) -_ResultT: Final = TypeVar("_ResultT") +_ResultT = TypeVar("_ResultT") _ASGI_APP: Final = TypeAdapter[ASGIApp](ASGIApp) _ROOT_PATH: Final = TypeAdapter(str) _JSON_OBJECT: Final = TypeAdapter(Mapping[str, object]) diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py index 624816f2697..9e52edd4730 100644 --- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py @@ -3091,7 +3091,7 @@ WebsocketUpstreamFrameClassifier: TypeAlias = Callable[[Mapping[str, object]], W _SESSION_FRAMES_EVERY_ROW_CARRIES: Final[frozenset[WebsocketUpstreamFrameKind]] = frozenset( {"opens_session", "updates_session"} ) -_FrameT: Final = TypeVar("_FrameT", bound=Mapping[str, object]) +_FrameT = TypeVar("_FrameT", bound=Mapping[str, object]) @dataclass(frozen=True, slots=True) diff --git a/litellm/proxy/pass_through_endpoints/success_handler.py b/litellm/proxy/pass_through_endpoints/success_handler.py index a418d7da04b..51ea09a979d 100644 --- a/litellm/proxy/pass_through_endpoints/success_handler.py +++ b/litellm/proxy/pass_through_endpoints/success_handler.py @@ -83,7 +83,7 @@ async def complete_despite_cancellation(work: Coroutine[object, object, None]) - raise -_HandlerParams: Final = ParamSpec("_HandlerParams") +_HandlerParams = ParamSpec("_HandlerParams") def _finishes_despite_cancellation_when_finalizing( diff --git a/litellm/proxy/roi_calculator/github.py b/litellm/proxy/roi_calculator/github.py index 922faaed992..c67eed3a03d 100644 --- a/litellm/proxy/roi_calculator/github.py +++ b/litellm/proxy/roi_calculator/github.py @@ -18,7 +18,7 @@ from litellm.types.llms.custom_http import httpxSpecialProvider from litellm.types.roi_calculator import ROIPullCommit, ROIPullEvidence, ROIPullFile, ROISettings from litellm.types.roi_observed import ObservedIssue -_T: Final = TypeVar("_T") +_T = TypeVar("_T") class SourceError(Exception): diff --git a/litellm/proxy/roi_calculator/gitlab.py b/litellm/proxy/roi_calculator/gitlab.py index ae53583ac5c..b961a02503f 100644 --- a/litellm/proxy/roi_calculator/gitlab.py +++ b/litellm/proxy/roi_calculator/gitlab.py @@ -19,7 +19,7 @@ from litellm.types.llms.custom_http import httpxSpecialProvider from litellm.types.roi_calculator import ROIPullCommit, ROIPullEvidence, ROIPullFile, ROISettings from litellm.types.roi_observed import ObservedIssue -_T: Final = TypeVar("_T", bound=BaseModel) +_T = TypeVar("_T", bound=BaseModel) class _User(LiteLLMBaseModel): diff --git a/litellm/proxy/search_endpoints/search_tool_registry.py b/litellm/proxy/search_endpoints/search_tool_registry.py index 31a5ddea999..2f686f0e2e7 100644 --- a/litellm/proxy/search_endpoints/search_tool_registry.py +++ b/litellm/proxy/search_endpoints/search_tool_registry.py @@ -175,8 +175,8 @@ def _did_not_decrypt(search_tool: Mapping[str, object]) -> bool: ) -_DbSearchToolT: Final = TypeVar("_DbSearchToolT", bound=Mapping[str, object]) -_LoadedSearchToolT: Final = TypeVar("_LoadedSearchToolT", bound=Mapping[str, object]) +_DbSearchToolT = TypeVar("_DbSearchToolT", bound=Mapping[str, object]) +_LoadedSearchToolT = TypeVar("_LoadedSearchToolT", bound=Mapping[str, object]) def keep_loaded_search_tools_that_do_not_decrypt( diff --git a/litellm/proxy/spend_tracking/spend_management_endpoints.py b/litellm/proxy/spend_tracking/spend_management_endpoints.py index 60bc71f5a72..abe77d001bf 100644 --- a/litellm/proxy/spend_tracking/spend_management_endpoints.py +++ b/litellm/proxy/spend_tracking/spend_management_endpoints.py @@ -142,8 +142,8 @@ class _DeploymentEntry(Protocol): def get(self, key: str, /) -> object: ... -_DeploymentT: Final = TypeVar("_DeploymentT", bound=_DeploymentEntry) -_DeploymentT_co: Final = TypeVar("_DeploymentT_co", bound=_DeploymentEntry, covariant=True) +_DeploymentT = TypeVar("_DeploymentT", bound=_DeploymentEntry) +_DeploymentT_co = TypeVar("_DeploymentT_co", bound=_DeploymentEntry, covariant=True) class _DeploymentRegistry(Protocol[_DeploymentT_co]): diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py index 997b0aec727..f0a20f2a1b5 100644 --- a/litellm/proxy/utils.py +++ b/litellm/proxy/utils.py @@ -395,7 +395,7 @@ if TYPE_CHECKING: else: Span = Any -_T: Final = TypeVar("_T") +_T = TypeVar("_T") class _RelTuplesRow(TypedDict): diff --git a/litellm/rag/rag_query.py b/litellm/rag/rag_query.py index e333015adc7..bfe58add990 100644 --- a/litellm/rag/rag_query.py +++ b/litellm/rag/rag_query.py @@ -9,7 +9,7 @@ from litellm.types.rerank import RerankResponse from litellm.types.utils import ModelResponse from litellm.types.vector_stores import VectorStoreSearchResponse -_ItemT: Final = TypeVar("_ItemT") +_ItemT = TypeVar("_ItemT") class _ResultContentView(TypedDict): diff --git a/litellm/repositories/budget_repository.py b/litellm/repositories/budget_repository.py index a60a9934b5b..12dc0f2b7b6 100644 --- a/litellm/repositories/budget_repository.py +++ b/litellm/repositories/budget_repository.py @@ -21,7 +21,7 @@ if TYPE_CHECKING: from prisma import models as prisma_models -_Row: Final = TypeVar("_Row") +_Row = TypeVar("_Row") _BUDGET_ROW: Final[TypeAdapter[Mapping[str, object]]] = TypeAdapter(Mapping[str, object]) diff --git a/litellm/repositories/chunked_in.py b/litellm/repositories/chunked_in.py index 7cd4d10c8e5..0e48c9424a6 100644 --- a/litellm/repositories/chunked_in.py +++ b/litellm/repositories/chunked_in.py @@ -21,8 +21,8 @@ IN_LIST_CHUNK_SIZE: Final = 5_000 MAX_IN_LIST_CHUNK_SIZE: Final = 30_000 LOGICAL_KEYS: Final = frozenset({"AND", "OR", "NOT"}) -RowT: Final = TypeVar("RowT") -ResultT: Final = TypeVar("ResultT") +RowT = TypeVar("RowT") +ResultT = TypeVar("ResultT") Atomicity: TypeAlias = Literal["caller_transaction", "per_chunk_ok"] """More than `chunk_size` values means more than one statement. `caller_transaction` diff --git a/litellm/responses/litellm_completion_transformation/compaction_items.py b/litellm/responses/litellm_completion_transformation/compaction_items.py index 8e9bffa961b..cade3ef50a0 100644 --- a/litellm/responses/litellm_completion_transformation/compaction_items.py +++ b/litellm/responses/litellm_completion_transformation/compaction_items.py @@ -17,7 +17,7 @@ from .tool_search import chat_config_builds_anthropic_request, provider_chat_con _JSON_OBJECT: Final = TypeAdapter(dict[str, object]) _OBJECT_LIST: Final = TypeAdapter(list[object]) -_Item: Final = TypeVar("_Item") +_Item = TypeVar("_Item") _INSTRUCTION_ROLES: Final = frozenset(("system", "developer")) diff --git a/litellm/responses/litellm_completion_transformation/tool_search_results.py b/litellm/responses/litellm_completion_transformation/tool_search_results.py index 8734ec932b9..a2e446835ea 100644 --- a/litellm/responses/litellm_completion_transformation/tool_search_results.py +++ b/litellm/responses/litellm_completion_transformation/tool_search_results.py @@ -28,8 +28,8 @@ from litellm.types.responses.main import OutputToolSearchCall, OutputToolSearchO from .custom_tools import openai_shaped_tool_call_item_id, serialize_tool_call_arguments from .tool_search import ANTHROPIC_TOOL_SEARCH_TOOL_NAME -_ItemT: Final = TypeVar("_ItemT") -_MessageT: Final = TypeVar("_MessageT") +_ItemT = TypeVar("_ItemT") +_MessageT = TypeVar("_MessageT") _MAPPING_ADAPTER: Final = TypeAdapter(Mapping[str, object]) _TOOL_SEARCH_ITEM_TYPES: Final = frozenset({"tool_search_call", "tool_search_output"}) diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.py index 43ec34d7f15..fdeaf03aaf4 100644 --- a/litellm/responses/litellm_completion_transformation/transformation.py +++ b/litellm/responses/litellm_completion_transformation/transformation.py @@ -324,8 +324,8 @@ _AUDIO_PART_ADAPTER: Final = TypeAdapter(ChatCompletionAudioObject) _IMAGE_URL_ADAPTER: Final = TypeAdapter(S3MediaImageUrlObject) _FILE_ADAPTER: Final = TypeAdapter(S3MediaFileObjectFile) _MessageT = TypeVar("_MessageT") -_MediaT: Final = TypeVar("_MediaT") -_InputItemT: Final = TypeVar("_InputItemT") +_MediaT = TypeVar("_MediaT") +_InputItemT = TypeVar("_InputItemT") _CACHED_CONTENT_ADAPTER: Final = TypeAdapter(ChatCompletionCachedContent) _DICT_ITEMS_LIST_ADAPTER: Final = TypeAdapter(list[dict[object, object]]) _TEXT_ADAPTER: Final = TypeAdapter(str) diff --git a/litellm/responses/utils.py b/litellm/responses/utils.py index edd55dc60e3..4d1510239f1 100644 --- a/litellm/responses/utils.py +++ b/litellm/responses/utils.py @@ -160,8 +160,8 @@ def _as_input_text_part(part: object) -> object: return part -_RequestInputT: Final = TypeVar("_RequestInputT") -_StreamEventT: Final = TypeVar("_StreamEventT", bound=BaseModel) +_RequestInputT = TypeVar("_RequestInputT") +_StreamEventT = TypeVar("_StreamEventT", bound=BaseModel) def _provider_mapped_params( diff --git a/litellm/router.py b/litellm/router.py index 439cab2293a..6a5c53b72f9 100644 --- a/litellm/router.py +++ b/litellm/router.py @@ -67,7 +67,7 @@ def _router_init( ## CACHING ## redis_url: str | None = None, redis_host: str | None = None, - redis_port: int | None = None, + redis_port: int | str | None = None, redis_password: str | None = None, redis_db: int | None = None, cache_responses: bool | None = False, @@ -126,7 +126,6 @@ def _router_init( fallback_rate_limit_check: FallbackRateLimitCheck | None = None, auto_router_capability_limit: AutoRouterCapabilityLimit | None = None, session_affinity_repin_on_failover: bool = False, - _host: PythonHost = python_host, enable_cross_model_group_collision_check: bool | None = None, ) -> None: """ @@ -136,7 +135,7 @@ def _router_init( model_list (Optional[list]): List of models to be used. Defaults to None. redis_url (Optional[str]): URL of the Redis server. Defaults to None. redis_host (Optional[str]): Hostname of the Redis server. Defaults to None. - redis_port (Optional[int]): Port of the Redis server. Defaults to None. + redis_port (int | str | None): Port of the Redis server. Defaults to None. redis_password (Optional[str]): Password of the Redis server. Defaults to None. cache_responses (Optional[bool]): Flag to enable caching of responses. Defaults to False. cache_kwargs (dict): Additional kwargs to pass to RedisCache. Defaults to {}. @@ -263,7 +262,7 @@ if TYPE_CHECKING: from litellm.types.utils import EmbeddingResponse, LiteLLMBatch, LiteLLMFineTuningJob, ModelResponse from litellm.types.vector_stores import VectorStoreCreateResponse - _P: Final = ParamSpec("_P") + _P = ParamSpec("_P") def _takes_parameters_of(source: Callable[_P, None]) -> Callable[[Callable[..., None]], Callable[_P, None]]: ... @@ -490,9 +489,7 @@ else: core: Final = self.__dict__.get("_core") return sorted({*super().__dir__(), *(dir(core) if core is not None else ())}) - Router.__init__.__signature__ = _CORE_SIGNATURE.replace( # pyright: ignore[reportFunctionMemberAccess] # inspect reads it - parameters=[parameter for parameter in _CORE_SIGNATURE.parameters.values() if parameter.name != "_host"] - ) + Router.__init__.__signature__ = _CORE_SIGNATURE # pyright: ignore[reportFunctionMemberAccess] # inspect reads it Router.__init__.__doc__ = _router_init.__doc__ diff --git a/litellm/router_deprecated.py b/litellm/router_deprecated.py index f21c0d3ea8d..922f733c239 100644 --- a/litellm/router_deprecated.py +++ b/litellm/router_deprecated.py @@ -62,8 +62,8 @@ if TYPE_CHECKING: ) from litellm.types.utils import ModelInfo as ModelMapInfo -_T: Final = TypeVar("_T") -_P: Final = ParamSpec("_P") +_T = TypeVar("_T") +_P = ParamSpec("_P") DEPRECATED_ROUTER_MEMBER_USES: Final[Counter[str]] = Counter() # mutable-ok: the live tally _note increments @@ -836,7 +836,7 @@ class DeprecatedRouterMembers: # Router-family functions and classes that took the Router (``litellm_router_instance=``, # ``router=``, ...) take its RoutingContext now. These keep the old spellings working. -_RoutingCallable: Final = TypeVar("_RoutingCallable", bound=Callable[..., object]) +_RoutingCallable = TypeVar("_RoutingCallable", bound=Callable[..., object]) @functools.cache diff --git a/litellm/router_rust/invoke/streaming.py b/litellm/router_rust/invoke/streaming.py index 57e65dbc07b..f28f72c34f7 100644 --- a/litellm/router_rust/invoke/streaming.py +++ b/litellm/router_rust/invoke/streaming.py @@ -96,7 +96,7 @@ _RESPONSES_TERMINAL_EVENT_TYPES: Final = ( # The hidden params and headers a fallback's response carries, as dicts the proxy writes into. _Prepared: TypeAlias = "tuple[dict[str, object], dict[str, object]]" -_RestT: Final = TypeVar("_RestT", Iterator[object], AsyncIterator[object]) +_RestT = TypeVar("_RestT", Iterator[object], AsyncIterator[object]) # --- the attempt a stream came from ------------------------------------------------------------- @@ -310,7 +310,7 @@ def _record_now(recording: Callable[[], object]) -> None: verbose_router_logger.warning("a stream's outcome was not recorded: %s", error) -_ItemT: Final = TypeVar("_ItemT") +_ItemT = TypeVar("_ItemT") async def _areported( diff --git a/litellm/router_utils/dynamic_queue.py b/litellm/router_utils/dynamic_queue.py index 6e4ddce331c..074e2ad646b 100644 --- a/litellm/router_utils/dynamic_queue.py +++ b/litellm/router_utils/dynamic_queue.py @@ -119,7 +119,7 @@ class Admitted: remaining_s: float -_R: Final = TypeVar("_R") +_R = TypeVar("_R") class QueueBackend(Protocol): diff --git a/litellm/router_utils/dynamic_queue_router.py b/litellm/router_utils/dynamic_queue_router.py index 4db2f064c1a..98cfd7f7471 100644 --- a/litellm/router_utils/dynamic_queue_router.py +++ b/litellm/router_utils/dynamic_queue_router.py @@ -104,7 +104,7 @@ def rejection_error(rejection: QueueTimeout | QueueFull, model: str) -> QueueRej assert_never(rejection) -_T: Final = TypeVar("_T") +_T = TypeVar("_T") async def _within(timer: Timer, seconds: float, call: Awaitable[_T]) -> _T | None: diff --git a/litellm/router_utils/endpoint_eligibility.py b/litellm/router_utils/endpoint_eligibility.py index 953c044d964..0ae6131b0a5 100644 --- a/litellm/router_utils/endpoint_eligibility.py +++ b/litellm/router_utils/endpoint_eligibility.py @@ -37,7 +37,7 @@ def _endpoint_path(endpoint: str) -> str: CHAT_ENDPOINTS: Final = frozenset(_endpoint_path(endpoint) for endpoint in CHAT_ENDPOINT_BY_CALL.values()) -_Deployment: Final = TypeVar("_Deployment", bound=Mapping[str, object]) +_Deployment = TypeVar("_Deployment", bound=Mapping[str, object]) _ENFORCE_FLAG: Final = TypeAdapter(bool | None) _REQUEST_SELECTION: Final[ContextVar[tuple[str | None, str | None]]] = ContextVar( "router_request_endpoint", default=(None, None) diff --git a/litellm/router_utils/kubernetes_pod_discovery.py b/litellm/router_utils/kubernetes_pod_discovery.py index b9140797174..e5e0aa8c600 100644 --- a/litellm/router_utils/kubernetes_pod_discovery.py +++ b/litellm/router_utils/kubernetes_pod_discovery.py @@ -40,7 +40,7 @@ _SyncLookup: TypeAlias = Future[list[_AddressInfo]] _AsyncLookup: TypeAlias = asyncio.Future[list[_AddressInfo]] _CacheKey: TypeAlias = tuple[str, int | None] _PodSelection: TypeAlias = tuple[str, int, Literal["round_robin", "session_affinity", "session_affinity_retry"]] -_DeploymentT: Final = TypeVar("_DeploymentT") +_DeploymentT = TypeVar("_DeploymentT") @dataclass(frozen=True, slots=True) @@ -563,9 +563,9 @@ class _HasPodDiscovery(Protocol): kubernetes_pod_discovery: KubernetesPodDiscovery -_P: Final = ParamSpec("_P") -_R: Final = TypeVar("_R") -_S: Final = TypeVar("_S", bound=_HasPodDiscovery) +_P = ParamSpec("_P") +_R = TypeVar("_R") +_S = TypeVar("_S", bound=_HasPodDiscovery) def _request_kwargs_from_call( diff --git a/litellm/router_utils/pre_call_checks/encrypted_content_affinity_check.py b/litellm/router_utils/pre_call_checks/encrypted_content_affinity_check.py index 8db5a5f0005..f97cd3276c3 100644 --- a/litellm/router_utils/pre_call_checks/encrypted_content_affinity_check.py +++ b/litellm/router_utils/pre_call_checks/encrypted_content_affinity_check.py @@ -72,7 +72,7 @@ if TYPE_CHECKING: from litellm.router_api import RoutingContext _REQUEST_KWARGS_ADAPTER: Final = TypeAdapter(Mapping[str, object]) -_DeploymentT: Final = TypeVar("_DeploymentT", bound=Mapping[str, object]) +_DeploymentT = TypeVar("_DeploymentT", bound=Mapping[str, object]) _HEADERS_ADAPTER: Final = TypeAdapter(Mapping[object, object]) _ACCOUNT_SCOPE_HEADERS: Final = frozenset({"openai-organization", "openai-project", "cookie"}) _SINGLE_VENDOR_PROVIDERS: Final = frozenset({LlmProviders.OPENAI.value}) diff --git a/litellm/rust_bridge/diagnostics.py b/litellm/rust_bridge/diagnostics.py index 90a5672a500..5d27c3947ce 100644 --- a/litellm/rust_bridge/diagnostics.py +++ b/litellm/rust_bridge/diagnostics.py @@ -6,7 +6,7 @@ from typing import Final, Protocol, TypeVar, cast from litellm.rust_bridge.bindings import NativeBinding -ResultT: Final = TypeVar("ResultT") +ResultT = TypeVar("ResultT") class NativeDiagnosticProcessor(Protocol): diff --git a/litellm/rust_bridge/dispatch.py b/litellm/rust_bridge/dispatch.py index ca98fe2b5b2..a6b75818fe4 100644 --- a/litellm/rust_bridge/dispatch.py +++ b/litellm/rust_bridge/dispatch.py @@ -9,9 +9,9 @@ from litellm.rust_bridge import catalog, runtime from litellm.rust_bridge.bindings import NativeBinding from litellm.rust_bridge.catalog import Route, RouteContext, Rules -RequestT: Final = TypeVar("RequestT") -NativeT: Final = TypeVar("NativeT") -ResultT: Final = TypeVar("ResultT") +RequestT = TypeVar("RequestT") +NativeT = TypeVar("NativeT") +ResultT = TypeVar("ResultT") NativeHook: TypeAlias = Callable[[RequestT, tuple[object, ...], Mapping[str, object]], ResultT] diff --git a/litellm/rust_bridge/execution.py b/litellm/rust_bridge/execution.py index a77fd162bf4..0227ecc6ea4 100644 --- a/litellm/rust_bridge/execution.py +++ b/litellm/rust_bridge/execution.py @@ -5,7 +5,7 @@ from contextlib import ExitStack from dataclasses import dataclass from typing import Final, Protocol, TypeVar, cast # noqa: TID251 # trusts the native stub at the binding boundary -_Call: Final = TypeVar("_Call") +_Call = TypeVar("_Call") @dataclass(frozen=True, slots=True) diff --git a/litellm/rust_bridge/host/routes/messages.py b/litellm/rust_bridge/host/routes/messages.py index fefbedeb6cf..493ca1e91ed 100644 --- a/litellm/rust_bridge/host/routes/messages.py +++ b/litellm/rust_bridge/host/routes/messages.py @@ -130,7 +130,7 @@ from litellm.types.router import GenericLiteLLMParams from litellm.types.utils import CallTypes, ProviderSpecificHeader, anthropic_wif_litellm_params from litellm.utils import clamp_max_tokens -_RaisedT: Final = TypeVar("_RaisedT", bound=Exception) +_RaisedT = TypeVar("_RaisedT", bound=Exception) _METADATA: Final = TypeAdapter(dict[str, object]) _BODY_FIELDS: Final = frozenset(_native.messages_optional_params()) diff --git a/litellm/rust_bridge/public_call.py b/litellm/rust_bridge/public_call.py index 0572d498b7d..9aa4b22d330 100644 --- a/litellm/rust_bridge/public_call.py +++ b/litellm/rust_bridge/public_call.py @@ -120,7 +120,7 @@ def native_call(legacy: inspect.Signature, args: tuple[object, ...], kwargs: Map return NativeCall(args=args, kwargs=kwargs, base=_without_bags(legacy, positional.arguments)) -NativeResultT: Final = TypeVar("NativeResultT") +NativeResultT = TypeVar("NativeResultT") def native_call_hook( diff --git a/litellm/rust_bridge/response_metadata.py b/litellm/rust_bridge/response_metadata.py index b5293bbe291..c8ddf3cff20 100644 --- a/litellm/rust_bridge/response_metadata.py +++ b/litellm/rust_bridge/response_metadata.py @@ -6,7 +6,7 @@ from litellm.litellm_core_utils.add_retry_fallback_headers import ( ) from litellm.rust_bridge.catalog import Route -ResultT: Final = TypeVar("ResultT") +ResultT = TypeVar("ResultT") def mark_rust_response(response: ResultT, route: Route) -> ResultT: diff --git a/litellm/scripts/check_type_discipline.py b/litellm/scripts/check_type_discipline.py index 574ba8cf3da..90c0adf6168 100644 --- a/litellm/scripts/check_type_discipline.py +++ b/litellm/scripts/check_type_discipline.py @@ -54,8 +54,11 @@ LIT010 Variable assignment without a `Final` declaration. Every local and modul that namespace is the SDK's runtime-settable config surface (users follow the documented `litellm.api_key = ...` pattern and the proxy rebinds these via setattr), and the package ships py.typed, so a Final there turns every - documented downstream assignment into a mypy error. Suppress a deliberately - rebindable name with `# rebind-ok: ` on each offending line. + documented downstream assignment into a mypy error. Type variables and type + aliases are the reverse: a `TypeVar`, `ParamSpec`, `TypeVarTuple`, or + `TypeAliasType` stays bare, and a Final one trips, since mypy reads it as a + plain variable instead of a type. Suppress a deliberately rebindable name + with `# rebind-ok: ` on each offending line. LIT011 Function-argument mutation: a parameter that is re-bound (`param = ...`, `param += ...`, a `for`/`with`/unpacking/walrus target, `del param`, or a re-bind in a nested function under `nonlocal param`) or mutated in place @@ -458,6 +461,7 @@ def iter_guard_violations(path: Path, tree: ast.AST) -> Iterator[Violation]: # --------------------------------------------------------------------------- # CONSTANT_DECLARATIONS = frozenset(("Final", "TypeAlias")) +TYPE_VARIABLE_FACTORIES = frozenset(("TypeVar", "ParamSpec", "TypeVarTuple", "TypeAliasType")) CONFIG_SURFACE_PARTS = ("litellm", "__init__.py") SELF_PARAMS = frozenset(("self", "cls")) NESTED_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda) @@ -480,6 +484,14 @@ def _declares_constant(annotation: ast.expr) -> bool: return isinstance(root, ast.Attribute) and root.attr in CONSTANT_DECLARATIONS +def _creates_type_variable(value: ast.expr | None) -> bool: + match value: + case ast.Call(func=ast.Name(id=name) | ast.Attribute(attr=name)): + return name in TYPE_VARIABLE_FACTORIES + case _: + return False + + def _defaults(args: ast.arguments) -> tuple[ast.expr, ...]: return (*args.defaults, *(d for d in args.kw_defaults if d is not None)) @@ -561,6 +573,8 @@ def _bound_names(target: ast.expr) -> Iterator[tuple[str, int]]: def _node_bindings(node: ast.AST, in_loop: bool) -> Iterator[Binding]: match node: + case ast.Assign(targets=[ast.Name(id=name, lineno=line)], value=value) if _creates_type_variable(value): + yield Binding(name, line, "other", in_loop) case ast.Assign(targets=targets): for target in targets: if isinstance(target, ast.Name): @@ -673,6 +687,23 @@ def iter_final_violations(path: Path, tree: ast.AST) -> Iterator[Violation]: ) +def iter_final_type_variable_violations(path: Path, tree: ast.AST) -> Iterator[Violation]: + for node in ast.walk(tree): + match node: + case ast.AnnAssign(target=ast.Name(id=name, lineno=line), annotation=annotation, value=value) if ( + _declares_constant(annotation) and _creates_type_variable(value) + ): + yield Violation( + path, + line, + "LIT010", + f"`{name}` is a type variable or type alias declared Final: mypy then reads it as a plain " + f"variable instead of a type, so remove the Final", + ) + case _: + pass + + def _mutation_sites(scope: ast.AST) -> Iterator[tuple[str, int]]: for node, _in_loop in _walk_scope(scope): match node: @@ -1034,9 +1065,7 @@ def _comprehension_owners(tree: ast.AST, ok_lines: frozenset[int]) -> Mapping[in silences a multi-line enclosing one and a violation sharing its only line can still be suppressed. """ - violating: Final = tuple( - n for n in ast.walk(tree) if isinstance(n, COMPREHENSION_NODES) and _violates(n) - ) + violating: Final = tuple(n for n in ast.walk(tree) if isinstance(n, COMPREHENSION_NODES) and _violates(n)) def nesting_key(node: ast.expr) -> tuple[int, int]: return (len(_span(node)), (node.end_col_offset or node.col_offset) - node.col_offset) @@ -1092,18 +1121,14 @@ def apply_suppressions( kept = tuple( v for v in raw - if not any( - v.line in suppressions.get(ok.token, frozenset()) and v.code in ok.codes - for ok in OK_SUPPRESSIONS - ) + if not any(v.line in suppressions.get(ok.token, frozenset()) and v.code in ok.codes for ok in OK_SUPPRESSIONS) ) unused = ( Violation( path, line, "LIT013", - f"`# {ok.token}` suppresses nothing: no " - f"{'/'.join(sorted(ok.codes))} violation on this line, so delete it", + f"`# {ok.token}` suppresses nothing: no {'/'.join(sorted(ok.codes))} violation on this line, so delete it", ) for ok in OK_SUPPRESSIONS for line in sorted(suppressions.get(ok.token, frozenset())) @@ -1130,9 +1155,7 @@ def check_file(path: Path) -> tuple[Violation, ...]: except SyntaxError as exc: return (*violations, Violation(path, exc.lineno or 0, "LIT000", f"syntax error: {exc.msg}")) - comprehension_violations: Final = tuple( - iter_comprehension_violations(path, tree, suppressions["comprehension-ok"]) - ) + comprehension_violations: Final = tuple(iter_comprehension_violations(path, tree, suppressions["comprehension-ok"])) return ( *violations, @@ -1144,6 +1167,7 @@ def check_file(path: Path) -> tuple[Violation, ...]: *iter_cast_violations(path, tree), *iter_guard_violations(path, tree), *iter_final_violations(path, tree), + *iter_final_type_variable_violations(path, tree), *iter_param_violations(path, tree), *iter_typeddict_violations(path, tree), *iter_pydantic_violations(path, tree), diff --git a/litellm/scripts/pre_commit_lint.sh b/litellm/scripts/pre_commit_lint.sh index e8fe0beb4d1..930825730b2 100755 --- a/litellm/scripts/pre_commit_lint.sh +++ b/litellm/scripts/pre_commit_lint.sh @@ -10,9 +10,12 @@ # with origin's current default branch, untracked files included # The per-area checks: # - litellm/ Python -> `make lint` (test-linting.yml's python job) -# - tests/e2e and tests/e2e_harness Python +# - tests/e2e, tests/e2e_harness, and litellm/proxy-extras Python, pyproject.toml, uv.lock # -> `make lint-e2e-basedpyright` (test-linting.yml's e2e type-check step) -# + raw HTTP client ban (test-linting.yml's check_e2e_no_raw_requests) +# - tests/e2e and tests/e2e_harness Python +# -> raw HTTP client ban (test-linting.yml's check_e2e_no_raw_requests) +# - litellm/router.py, litellm/__init__.py, uv.lock +# -> mypy Router stub guard (test-linting.yml's check_router_constructor_stub) # - tests/ Python, .github/linters/ruff-tests.toml, litellm/scripts/check_test_quality.py, # litellm/scripts/test_quality_gate.py # -> ruff over .github/linters/ruff-tests.toml + `make lint-test-quality` (test-linting.yml's @@ -98,6 +101,7 @@ existing_files() { litellm_py_pattern='^litellm/.*\.py$' e2e_py_pattern='^tests/e2e(_harness)?/.*\.py$' +e2e_types_pattern='^(tests/e2e(_harness)?/.*\.py|litellm/proxy-extras/.*\.py|pyproject\.toml|uv\.lock)$' test_tree_pattern='^(tests/.*\.py|\.github/linters/ruff-tests\.toml|pyproject\.toml|litellm/scripts/(check_test_quality|test_quality_gate)\.py)$' spec_pattern='^(litellm/.*|enterprise/.*|pyproject\.toml|uv\.lock|litellm/ui/litellm-dashboard/(scripts/gen-api-types\.mjs|package\.json|package-lock\.json|src/lib/http/schema\.d\.ts))$' ui_prettier_pattern='^litellm/ui/litellm-dashboard/.*\.(js|jsx|ts|tsx|mjs|cjs|json|css|scss|md|mdx|yml|yaml|html)$' @@ -107,7 +111,11 @@ litellm_py_files=$(scope_match "$litellm_py_pattern" | grep -Ev '^litellm/(enter if [ -n "$(scope_match '^(litellm/proxy/mcp_server/|litellm/scripts/check_mcp_operation_boundary\.py)')" ]; then uv run --no-sync python litellm/scripts/check_mcp_operation_boundary.py || exit 1 fi +if [ -n "$(scope_match '^(litellm/(router|__init__)\.py|tests/code_coverage_tests/check_router_constructor_stub\.py|uv\.lock)$')" ]; then + uv run --no-sync python tests/code_coverage_tests/check_router_constructor_stub.py || exit 1 +fi e2e_py_files=$(scope_match "$e2e_py_pattern") +e2e_types_files=$(scope_match "$e2e_types_pattern") test_tree_files=$(scope_match "$test_tree_pattern") # ruff format (and CI's format step) skip enterprise; the rest of make lint covers it. fmt_files=$(printf '%s\n' "$litellm_py_files" | grep -v '^litellm/enterprise/' | existing_files) @@ -147,7 +155,8 @@ if [ -n "$staged" ]; then printf '%s\n' "$missed" | sed 's/^/ /' >&2 } warn_skipped "Python lint (make lint)" "$litellm_py_pattern" "$litellm_py_files" - warn_skipped "tests/e2e checks (basedpyright + raw HTTP client ban)" "$e2e_py_pattern" "$e2e_py_files" + warn_skipped "tests/e2e basedpyright" "$e2e_types_pattern" "$e2e_types_files$litellm_py_files" + warn_skipped "tests/e2e raw HTTP client ban" "$e2e_py_pattern" "$e2e_py_files" warn_skipped "test-tree lint (.github/linters/ruff-tests.toml + test-quality gate)" "$test_tree_pattern" "$test_tree_files" warn_skipped "dashboard lint (prettier + eslint + lint budgets)" "$ui_prettier_pattern" "$ui_prettier_changed" warn_skipped "dashboard API-type sync (npm run gen:api)" "$spec_pattern" "$spec_files" @@ -227,7 +236,7 @@ if [ -n "$litellm_py_files" ]; then set +m fi -if [ -n "$e2e_py_files" ] && [ -z "$litellm_py_files" ]; then +if [ -n "$e2e_types_files" ] && [ -z "$litellm_py_files" ]; then echo "check: type-checking tests/e2e (make lint-e2e-basedpyright)" make lint-e2e-basedpyright || { echo "✗ tests/e2e basedpyright failed. Fix the errors above, then re-run make check." >&2; status=1; } fi @@ -334,13 +343,15 @@ summary_item() { echo "check: summary" summary_item "Python lint (make lint)" "$litellm_py_files" "no litellm/ Python files in scope" -summary_item "tests/e2e checks (basedpyright + raw HTTP client ban)" "$e2e_py_files" "no tests/e2e Python files in scope" +summary_item "tests/e2e basedpyright" "$e2e_types_files$litellm_py_files" \ + "no litellm/, tests/e2e, or litellm/proxy-extras Python, or type-check inputs in scope" +summary_item "tests/e2e raw HTTP client ban" "$e2e_py_files" "no tests/e2e Python files in scope" summary_item "test-tree lint (.github/linters/ruff-tests.toml + test-quality gate)" "$test_tree_files" \ "no tests/ Python files or test-tree lint inputs in scope" summary_item "dashboard lint (prettier + eslint + lint budgets)" "$ui_prettier_changed$ui_eslint_changed" "no dashboard files in scope" summary_item "dashboard API-type sync (npm run gen:api)" "$spec_files" "no litellm/, enterprise/, dependency, or generator files in scope" -if [ -z "$litellm_py_files$e2e_py_files$test_tree_files$ui_prettier_changed$ui_eslint_changed$spec_files" ]; then +if [ -z "$litellm_py_files$e2e_types_files$test_tree_files$ui_prettier_changed$ui_eslint_changed$spec_files" ]; then echo "check: NOTE - no gating lint check matches the files in scope, so nothing ran:" >&2 printf '%s\n' "$scope" | sed 's/^/ /' >&2 echo " A pass here is a no-op, not a lint verdict." >&2 diff --git a/litellm/telemetry/aggregate.py b/litellm/telemetry/aggregate.py index f875026c74d..f56ff210b5e 100644 --- a/litellm/telemetry/aggregate.py +++ b/litellm/telemetry/aggregate.py @@ -12,8 +12,8 @@ QUIET_RETRIES: Final = 3 _LOGGER: Final = logging.getLogger(__name__) -_Key: Final = TypeVar("_Key") -_Row: Final = TypeVar("_Row") +_Key = TypeVar("_Key") +_Row = TypeVar("_Row") class AggregatingSink: diff --git a/litellm/types/integrations/custom_logger_v2.py b/litellm/types/integrations/custom_logger_v2.py index 9bf3ab091cd..637ff7a9539 100644 --- a/litellm/types/integrations/custom_logger_v2.py +++ b/litellm/types/integrations/custom_logger_v2.py @@ -18,8 +18,8 @@ from pydantic import Field as Member _LOGGER: Final = logging.getLogger("LiteLLM") -RecordT: Final = TypeVar("RecordT", bound=BaseModel) -ValueT: Final = TypeVar("ValueT") +RecordT = TypeVar("RecordT", bound=BaseModel) +ValueT = TypeVar("ValueT") I64: TypeAlias = Annotated[int, Member(ge=-(2**63), le=2**63 - 1)] diff --git a/litellm/types/rerank.py b/litellm/types/rerank.py index 40fc46fcc3f..b27eb664b10 100644 --- a/litellm/types/rerank.py +++ b/litellm/types/rerank.py @@ -80,7 +80,7 @@ class RerankUsage(TypedDict): _RERANK_META: Final = TypeAdapter(RerankResponseMeta) _FIELD_VALUE: Final = TypeAdapter(object) -_Default: Final = TypeVar("_Default") +_Default = TypeVar("_Default") def get_rerank_usage(response: Mapping[str, object]) -> RerankUsage | None: diff --git a/litellm/types/router.py b/litellm/types/router.py index da276f780e2..2bdac0d1c66 100644 --- a/litellm/types/router.py +++ b/litellm/types/router.py @@ -563,7 +563,7 @@ _RESERVED_INIT_KEYS: Final = frozenset({"self", "params", "__class__"}) _STRICT_LITELLM_PARAMS: Final = MappingProxyType({"strict_litellm_params": True}) -_StrictlyValidatedParams: Final = TypeVar("_StrictlyValidatedParams", bound=BaseModel) +_StrictlyValidatedParams = TypeVar("_StrictlyValidatedParams", bound=BaseModel) def validate_litellm_params_strictly( diff --git a/litellm/utils.py b/litellm/utils.py index 698a6995811..99655340751 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -884,7 +884,7 @@ _OIDC_TOKEN_FETCH_EXECUTOR: Final = ThreadPoolExecutor(thread_name_prefix="litel _PASS_THROUGH_CALL_TYPES: Final = frozenset( {CallTypes.allm_passthrough_route.value, CallTypes.llm_passthrough_route.value} ) -_Resolved: Final = TypeVar("_Resolved") +_Resolved = TypeVar("_Resolved") async def _resolved_off_the_event_loop(resolve: Callable[[OidcResolver], _Resolved], api_key: object) -> _Resolved: @@ -4426,7 +4426,7 @@ def is_generalized_model_info(model_info: ModelInfoBase) -> bool: _REGISTRATION_ATTEMPTS: Final = 3 -_ModelInfoT: Final = TypeVar("_ModelInfoT", bound=ModelInfoBase) +_ModelInfoT = TypeVar("_ModelInfoT", bound=ModelInfoBase) def _lookup_mapped_model_info(lookup: Callable[[], _ModelInfoT]) -> _ModelInfoT | ModelInfoLookupMiss: diff --git a/litellm/vector_stores/search_query.py b/litellm/vector_stores/search_query.py index 6ee7c4579df..aa3044b6cb9 100644 --- a/litellm/vector_stores/search_query.py +++ b/litellm/vector_stores/search_query.py @@ -13,7 +13,7 @@ from litellm.litellm_core_utils.core_helpers import as_object_list, as_str_mappi from litellm.types.vector_stores import RETRIEVAL_QUERY_PARAMS, VectorStoreSearchQueryImage _QUERY_IMAGE: Final = TypeAdapter(VectorStoreSearchQueryImage) -_Query: Final = TypeVar("_Query", bound=str | Sequence[str]) +_Query = TypeVar("_Query", bound=str | Sequence[str]) _CALLER_QUERY_PARAMS: Final = ("query_image", *RETRIEVAL_QUERY_PARAMS) _BASE64_LINE_BREAKS: Final = str.maketrans("", "", "\r\n") diff --git a/tests/code_coverage_tests/check_router_constructor_stub.py b/tests/code_coverage_tests/check_router_constructor_stub.py new file mode 100644 index 00000000000..eb69f7b527b --- /dev/null +++ b/tests/code_coverage_tests/check_router_constructor_stub.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Fail unless mypy reads the Router constructor stub in litellm/router.py through `from litellm import Router`. + +litellm ships py.typed, so a stub that mypy reads as Any accepts every argument name in SDK users' code, +while basedpyright, which `make lint-e2e-basedpyright` runs, can still read it. +""" + +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Final + +PROBE: Final = """\ +from litellm import Router + +Router(model_list=[], num_retries=2) +Router(model_list=[], redis_host="localhost", redis_port="6379") +Router(model_list=[], not_a_parameter=1) +""" +EXPECTED_ERROR: Final = 'Unexpected keyword argument "not_a_parameter" for "Router"' + + +def mypy_errors(probe: Path) -> tuple[str, ...]: + completed: Final = subprocess.run( + ( + sys.executable, + "-I", + "-m", + "mypy", + "--config-file=", + "--follow-imports=skip", + "--ignore-missing-imports", + "litellm/__init__.py", + "litellm/router.py", + str(probe), + ), + capture_output=True, + text=True, + check=False, + ) + return tuple(line for line in completed.stdout.splitlines() if ": error: " in line) + + +def main() -> int: + with tempfile.TemporaryDirectory() as directory: + probe: Final = Path(directory) / "router_constructor_probe.py" + probe.write_text(PROBE) + errors: Final = mypy_errors(probe) + probe_errors: Final = tuple(error for error in errors if Path(error.partition(":")[0]).name == probe.name) + if len(probe_errors) == 1 and EXPECTED_ERROR in probe_errors[0]: + print("mypy reads the Router constructor stub") + return 0 + print(f"expected only {EXPECTED_ERROR!r} from the probe, got: {errors}") + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/e2e/AGENTS.md b/tests/e2e/AGENTS.md index af01467d496..1ee70cee574 100644 --- a/tests/e2e/AGENTS.md +++ b/tests/e2e/AGENTS.md @@ -130,7 +130,7 @@ Current limits: Bedrock cannot be mounted in record or replay (SigV4 signs the H ## Typing -The harness is fully typed with no error budget: `make lint-e2e-basedpyright` must report zero basedpyright errors, and CI enforces that on any PR touching `tests/e2e/**/*.py`. When a response field is untyped, model it in `models.py` (just the fields you read) and let pydantic validate it, rather than threading a `dict` or `Any` through the test +The harness is fully typed with no error budget: `make lint-e2e-basedpyright` must report zero basedpyright errors, and CI enforces that on any PR touching `tests/e2e/**/*.py`, `tests/e2e_harness/**/*.py`, `litellm/**/*.py`, `pyproject.toml` or `uv.lock`. When a response field is untyped, model it in `models.py` (just the fields you read) and let pydantic validate it, rather than threading a `dict` or `Any` through the test ## Typed test metadata diff --git a/tests/e2e/CONTRIBUTING.md b/tests/e2e/CONTRIBUTING.md index f451c635d11..06e4c225de1 100644 --- a/tests/e2e/CONTRIBUTING.md +++ b/tests/e2e/CONTRIBUTING.md @@ -199,7 +199,7 @@ Mark live tests with `@pytest.mark.e2e` (on the class or the module). Pure cover Before you push -1. Run `make lint-e2e-basedpyright` (or `make check` with your changes staged); the harness is fully typed and the gate allows zero basedpyright errors, enforced in CI on any PR touching `tests/e2e/**/*.py` or `tests/e2e_harness/**/*.py` +1. Run `make lint-e2e-basedpyright` (or `make check` with your changes staged); the harness is fully typed and the gate allows zero basedpyright errors, enforced in CI on any PR touching `tests/e2e/**/*.py`, `tests/e2e_harness/**/*.py`, `litellm/**/*.py`, `pyproject.toml`, or `uv.lock` 2. Add the models your test needs to the config your local proxy loads diff --git a/tests/integration/compatibility/test_openai_sdk_client_paths.py b/tests/integration/compatibility/test_openai_sdk_client_paths.py index d6b6d1d460d..46cf986e498 100644 --- a/tests/integration/compatibility/test_openai_sdk_client_paths.py +++ b/tests/integration/compatibility/test_openai_sdk_client_paths.py @@ -78,7 +78,7 @@ SPEECH_UPSTREAM_MODEL: Final = "gpt-4o-mini-tts" PAYMENT_REQUIRED_DEPLOYMENTS: Final[Mapping[str, str]] = MappingProxyType( {"openai": "openai/gpt-4o-mini", "anthropic": "anthropic/claude-sonnet-4-5"} ) -_R: Final = TypeVar("_R") +_R = TypeVar("_R") def _identity(prefix: str) -> str: diff --git a/tests/integration/sdk/test_openai_sdk_client_sessions_wire.py b/tests/integration/sdk/test_openai_sdk_client_sessions_wire.py index e8ec1a37082..c67b65fdc66 100644 --- a/tests/integration/sdk/test_openai_sdk_client_sessions_wire.py +++ b/tests/integration/sdk/test_openai_sdk_client_sessions_wire.py @@ -21,7 +21,7 @@ from litellm import Router from litellm.llms.base_llm.chat.transformation import BaseLLMException from litellm.types.utils import ImageResponse, ModelResponse, TextCompletionResponse -_R: Final = TypeVar("_R") +_R = TypeVar("_R") _PROVIDER_KEY: Final = "sk-scripted-provider" _API_VERSION: Final = "2024-10-21" diff --git a/tests/unit/proxy/proxy_server/conftest.py b/tests/unit/proxy/proxy_server/conftest.py index 3c13b9285c6..60be27aab2e 100644 --- a/tests/unit/proxy/proxy_server/conftest.py +++ b/tests/unit/proxy/proxy_server/conftest.py @@ -29,8 +29,8 @@ if TYPE_CHECKING: from tests.unit.proxy.router_entry_point_stubs import route_entry_points_to_stubs -_OffloadParams: Final = ParamSpec("_OffloadParams") -_OffloadResult: Final = TypeVar("_OffloadResult") +_OffloadParams = ParamSpec("_OffloadParams") +_OffloadResult = TypeVar("_OffloadResult") @pytest.fixture diff --git a/tests/unit/test_check_type_discipline.py b/tests/unit/test_check_type_discipline.py index f67a51d476c..f771bf81bb8 100644 --- a/tests/unit/test_check_type_discipline.py +++ b/tests/unit/test_check_type_discipline.py @@ -303,6 +303,39 @@ def test_single_leading_underscore_is_not_exempt(tmp_path): assert "LIT010" in _codes(tmp_path, "_x = 1\n") +@pytest.mark.parametrize( + "declaration", + ( + "TypeVar('_T')", + "ParamSpec('_T')", + "TypeVarTuple('_T')", + "TypeAliasType('_T', int)", + "typing.TypeVar('_T')", + "typing_extensions.ParamSpec('_T')", + ), +) +def test_a_type_variable_stays_bare_and_a_final_one_trips(tmp_path: Path, declaration: str) -> None: + assert "LIT010" not in _codes(tmp_path, f"_T = {declaration}\n") + assert "LIT010" in _codes(tmp_path, f"_T: Final = {declaration}\n") + assert "LIT010" in _codes(tmp_path, f"_T: Final[object] = {declaration}\n") + + +def test_a_final_type_variable_trips_in_a_class_body(tmp_path: Path) -> None: + assert "LIT010" in _codes(tmp_path, "class Box:\n _T: Final = TypeVar('_T')\n") + + +def test_a_final_type_variable_trips_on_the_config_surface(tmp_path: Path) -> None: + assert "LIT010" in _codes_at(tmp_path, ("litellm", "__init__.py"), "_T: Final = TypeVar('_T')\n") + + +def test_rebinding_a_bare_type_variable_still_trips(tmp_path: Path) -> None: + assert "LIT010" in _codes(tmp_path, "_T = TypeVar('_T')\n_T = 1\n") + + +def test_a_final_call_to_any_other_factory_stays_clean(tmp_path: Path) -> None: + assert "LIT010" not in _codes(tmp_path, "limit: Final = int('1')\n") + + def test_rebind_ok_suppresses_a_repeated_unpack(tmp_path): src = "a, b = (1, 2)\na, b = (b, a) # rebind-ok: swap in place\n" assert "LIT010" not in _codes(tmp_path, src) diff --git a/tests/unit/test_lint_workflow_diff_gates.py b/tests/unit/test_lint_workflow_diff_gates.py index c9a5623d742..5406238d051 100644 --- a/tests/unit/test_lint_workflow_diff_gates.py +++ b/tests/unit/test_lint_workflow_diff_gates.py @@ -246,7 +246,10 @@ def test_diff_gate_selects_top_level_and_nested_python_files_only(tmp_path: Path ( "tests/e2e_harness/top_level_module.py", "tests/e2e_harness/pkg/sub/nested_module.py", + "litellm/router.py", + "litellm/proxy-extras/litellm_proxy_extras/pkg/nested_module.py", "pyproject.toml", + "uv.lock", ), ) def test_e2e_basedpyright_gate_also_fires_on_harness_python_and_pyrightconfig(tmp_path: Path, trigger: str) -> None: diff --git a/tests/unit/test_pre_commit_lint.py b/tests/unit/test_pre_commit_lint.py index 53cbb43d393..10d7d8c1e45 100644 --- a/tests/unit/test_pre_commit_lint.py +++ b/tests/unit/test_pre_commit_lint.py @@ -85,6 +85,10 @@ case "$*" in [ -n "${STUB_ARGS_DIR:-}" ] && echo "$*" >> "$STUB_ARGS_DIR/ruff_tests.args" [ "${STUB_FAIL:-}" = "tests-ruff" ] && exit 1 ;; + "run --no-sync python tests/code_coverage_tests/check_router_constructor_stub.py") + [ -n "${STUB_ARGS_DIR:-}" ] && echo "$*" >> "$STUB_ARGS_DIR/router_stub.args" + [ "${STUB_FAIL:-}" = "router-stub" ] && exit 1 + ;; esac exit 0 """ @@ -421,12 +425,56 @@ def test_run_ends_with_a_summary_of_ran_and_skipped_blocks(tmp_path: Path) -> No assert "ran: Python lint (make lint)" in proc.stdout assert "ran: dashboard lint (prettier + eslint + lint budgets)" in proc.stdout assert "ran: dashboard API-type sync (npm run gen:api)" in proc.stdout - assert "skipped: tests/e2e checks (basedpyright + raw HTTP client ban) (no tests/e2e Python files in scope)" in proc.stdout + assert "ran: tests/e2e basedpyright" in proc.stdout + assert "skipped: tests/e2e raw HTTP client ban (no tests/e2e Python files in scope)" in proc.stdout assert TEST_TREE_SKIPPED in proc.stdout assert "check: PASS" in proc.stdout assert "check: FAIL" not in proc.stdout +@pytest.mark.parametrize( + "type_input", + ( + "tests/e2e_harness/collector.py", + "litellm/proxy-extras/litellm_proxy_extras/utils.py", + "pyproject.toml", + "uv.lock", + ), +) +def test_an_e2e_type_check_input_alone_runs_the_e2e_basedpyright_step(tmp_path: Path, type_input: str) -> None: + repo, bin_dir = _sandbox(tmp_path) + _commit_all(repo, "base") + args_dir = tmp_path / "args" + args_dir.mkdir() + _stage_file(repo, type_input, "x = 1\n") + proc = _run(repo, bin_dir, {"STUB_ARGS_DIR": str(args_dir)}) + assert proc.returncode == 0, proc.stdout + proc.stderr + assert "lint-e2e-basedpyright" in _recorded(args_dir, "make.args") + assert "ran: tests/e2e basedpyright" in proc.stdout + + +@pytest.mark.parametrize( + ("changed", "runs"), (("litellm/router.py", True), ("litellm/__init__.py", True), ("litellm/foo.py", False)) +) +def test_the_router_stub_guard_runs_only_when_the_router_changes(tmp_path: Path, changed: str, runs: bool) -> None: + repo, bin_dir = _sandbox(tmp_path) + _commit_all(repo, "base") + args_dir = tmp_path / "args" + args_dir.mkdir() + _stage_file(repo, changed, "x = 3\n") + proc = _run(repo, bin_dir, {"STUB_ARGS_DIR": str(args_dir)}) + assert proc.returncode == 0, proc.stdout + proc.stderr + assert (args_dir / "router_stub.args").exists() is runs + + +def test_a_failing_router_stub_guard_fails_the_run(tmp_path: Path) -> None: + repo, bin_dir = _sandbox(tmp_path) + _commit_all(repo, "base") + _stage_file(repo, "litellm/router.py", "x = 3\n") + proc = _run(repo, bin_dir, {"STUB_FAIL": "router-stub"}) + assert proc.returncode == 1 + + @pytest.mark.parametrize( "spec_input", (