mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-23 13:22:58 +08:00
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
This commit is contained in:
1 parent
151a6392de
commit
3ccc619792
133 files changed
+376
-201
No files matched your search
@@ -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
|
||||
|
||||
@@ -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: <reason>`
|
||||
- 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: <reason>`
|
||||
- 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: <reason>`
|
||||
- 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: <reason>` 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: <reason>` on the `class` line
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ else:
|
||||
Span = Any
|
||||
|
||||
|
||||
_T: Final = TypeVar("_T")
|
||||
_T = TypeVar("_T")
|
||||
|
||||
|
||||
def _connection_limit(max_connections: object) -> int | None:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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]
|
||||
|
||||
|
||||
@@ -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__"
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
|
||||
@@ -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]):
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)])
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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(
|
||||
(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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]
|
||||
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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]]]
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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})
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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])
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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]]]
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -60,7 +60,7 @@ class OpenAILikeBase:
|
||||
return api_base, headers
|
||||
|
||||
|
||||
_HeaderValue: Final = TypeVar("_HeaderValue")
|
||||
_HeaderValue = TypeVar("_HeaderValue")
|
||||
|
||||
|
||||
def with_canonical_authorization(
|
||||
|
||||
@@ -14,7 +14,7 @@ from litellm.types.decisions import (
|
||||
OpenAIDecisionInputTokensDetails,
|
||||
)
|
||||
|
||||
_Model: Final = TypeVar("_Model", bound=BaseModel)
|
||||
_Model = TypeVar("_Model", bound=BaseModel)
|
||||
|
||||
|
||||
class _ProviderAttempt(BaseModel):
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"})
|
||||
|
||||
@@ -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, ...]:
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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("/")
|
||||
|
||||
@@ -50,7 +50,7 @@ class CodexStock:
|
||||
instructions: str
|
||||
|
||||
|
||||
_Value: Final = TypeVar("_Value")
|
||||
_Value = TypeVar("_Value")
|
||||
|
||||
|
||||
class CodexReleaseClient(Protocol):
|
||||
|
||||
@@ -299,7 +299,7 @@ def decrypt_bearer_token(token: str, prefix: str) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
_Passthrough: Final = TypeVar("_Passthrough")
|
||||
_Passthrough = TypeVar("_Passthrough")
|
||||
|
||||
|
||||
@overload
|
||||
|
||||
@@ -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]])
|
||||
|
||||
|
||||
|
||||
@@ -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]):
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"])
|
||||
|
||||
|
||||
@@ -628,7 +628,7 @@ def _coerce_timeout(value: object, fallback: float) -> float:
|
||||
return fallback
|
||||
|
||||
|
||||
_ReadResultT: Final = TypeVar("_ReadResultT")
|
||||
_ReadResultT = TypeVar("_ReadResultT")
|
||||
|
||||
|
||||
class _DBReconnectClient(Protocol):
|
||||
|
||||
@@ -275,7 +275,7 @@ class _PrismaDrainTracker:
|
||||
await self._drained.wait()
|
||||
|
||||
|
||||
_EngineResponseT: Final = TypeVar("_EngineResponseT")
|
||||
_EngineResponseT = TypeVar("_EngineResponseT")
|
||||
|
||||
|
||||
class _TrackedPrismaEngine:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"[.!?]+")
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -58,7 +58,7 @@ from litellm.types.repositories.daily_activity import (
|
||||
SpendLogsWindow,
|
||||
)
|
||||
|
||||
_T: Final = TypeVar("_T")
|
||||
_T = TypeVar("_T")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
||||
@@ -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"})
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
+1
-1
@@ -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, ...])
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -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]):
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -200,7 +200,7 @@ class TransactionSource(Protocol):
|
||||
def tx(self) -> AbstractAsyncContextManager["Prisma"]: ...
|
||||
|
||||
|
||||
T: Final = TypeVar("T")
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
||||
@@ -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]]:
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -21,7 +21,7 @@ if TYPE_CHECKING:
|
||||
|
||||
from litellm.router import Router
|
||||
|
||||
_Tool: Final = TypeVar("_Tool")
|
||||
_Tool = TypeVar("_Tool")
|
||||
|
||||
|
||||
class SemanticToolFilterContextWindowError(Exception):
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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]):
|
||||
|
||||
@@ -395,7 +395,7 @@ if TYPE_CHECKING:
|
||||
else:
|
||||
Span = Any
|
||||
|
||||
_T: Final = TypeVar("_T")
|
||||
_T = TypeVar("_T")
|
||||
|
||||
|
||||
class _RelTuplesRow(TypedDict):
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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])
|
||||
|
||||
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -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"))
|
||||
|
||||
|
||||
|
||||
@@ -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"})
|
||||
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user