The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_decrease_anys_opus5
mateo-berri8d4620649fa7
diff --cc basedpyright-code-budget.jsonindex 58b8ae01cb0,122bd82c657..3fa30f96dea--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@@ -1,18 -1,18 +1,18 @@@{"reportAny": {- "limit": 18773- "limit": 18483++ "limit": 15800},"reportArgumentType": {- "limit": 2566- "limit": 2557++ "limit": 2262},"reportAssignmentType": {- "limit": 319+ "limit": 320},"reportAttributeAccessIssue": {- "limit": 480+ "limit": 488},"reportCallIssue": {- "limit": 113+ "limit": 114},"reportConstantRedefinition": {"limit": 40@@@ -24,7 -24,7 +24,7 @@@"limit": 19},"reportExplicitAny": {- "limit": 5774- "limit": 5960++ "limit": 5174},"reportFunctionMemberAccess": {"limit": 7@@@ -54,10 -54,10 +54,10 @@@"limit": 0},"reportMissingParameterType": {- "limit": 5640- "limit": 5659++ "limit": 5590},"reportMissingTypeArgument": {- "limit": 15498- "limit": 15482++ "limit": 15327},"reportMissingTypeStubs": {"limit": 40@@@ -72,7 -72,7 +72,7 @@@"limit": 0},"reportOptionalMemberAccess": {- "limit": 1061- "limit": 1058++ "limit": 0},"reportOptionalOperand": {"limit": 0@@@ -90,7 -90,7 +90,7 @@@"limit": 8},"reportReturnType": {-- "limit": 213++ "limit": 181},"reportTypedDictNotRequiredAccess": {"limit": 26@@@ -99,31 -99,31 +99,31 @@@"limit": 0},"reportUnknownArgumentType": {- "limit": 44589- "limit": 44526++ "limit": 44375},"reportUnknownLambdaType": {"limit": 109},"reportUnknownMemberType": {- "limit": 38882- "limit": 38779++ "limit": 38487},"reportUnknownParameterType": {- "limit": 19806- "limit": 19827++ "limit": 19590},"reportUnknownVariableType": {- "limit": 30456- "limit": 30348++ "limit": 30126},"reportUnnecessaryCast": {- "limit": 116- "limit": 117++ "limit": 113},"reportUnnecessaryComparison": {- "limit": 698+ "limit": 697},"reportUnnecessaryContains": {"limit": 5},"reportUnnecessaryIsInstance": {- "limit": 835- "limit": 831++ "limit": 834},"reportUntypedBaseClass": {"limit": 0@@@ -135,12 -135,12 +135,12 @@@"limit": 21},"reportUnusedFunction": {- "limit": 138+ "limit": 139},"reportUnusedImport": {-- "limit": 544++ "limit": 541},"reportUnusedVariable": {- "limit": 142- "limit": 145++ "limit": 133}}diff --cc litellm/caching/valkey_semantic_cache.pyindex ac4d4033546,c66f6873383..58b76d98d6d--- a/litellm/caching/valkey_semantic_cache.py+++ b/litellm/caching/valkey_semantic_cache.py@@@ -63,7 -63,8 +64,8 @@@ class ValkeySemanticCache(RedisSemanticsync_client: Redis | None = None,async_client: AsyncRedis | None = None,embedding_max_input_tokens: int | None = None,+ embedding_timeout: float | None = None,- **kwargs: Any,+ **kwargs: object,):if similarity_threshold is None:raise ValueError("similarity_threshold must be provided, passed None")@@@ -85,11 -87,11 +88,13 @@@self.key_prefix = f"{self.index_name}:"self._index_dim: int | None = None-- resolved_url = None-- if sync_client is None or async_client is None:-- resolved_url = redis_url or self._build_valkey_url(host, port, password, ssl)-- self.sync_client = sync_client if sync_client is not None else Redis.from_url(resolved_url)-- self.async_client = async_client if async_client is not None else AsyncRedis.from_url(resolved_url)++ if sync_client is not None and async_client is not None:++ self.sync_client = sync_client++ self.async_client = async_client++ else:++ resolved_url: Final = redis_url or self._build_valkey_url(host, port, password, ssl)++ self.sync_client = sync_client if sync_client is not None else Redis.from_url(resolved_url)++ self.async_client = async_client if async_client is not None else AsyncRedis.from_url(resolved_url)print_verbose(f"Valkey semantic-cache initializing index - {self.index_name}")@@@ -208,16 -208,9 +213,16 @@@)return Query(query_string).return_fields(self.RESPONSE_FIELD_NAME, self.DISTANCE_FIELD_NAME).dialect(2)+ async def _async_search(self, key: str, embedding: Sequence[float]) -> object:+ """Run the KNN query on the async client, stopping the untyped search surface here."""+ return await self.async_client.ft(self.index_name).search(+ self._knn_query(key),- query_params={"vec": self._embedding_to_bytes(embedding)},++ query_params={"vec": self._embedding_to_bytes(embedding)}, # pyright: ignore[reportArgumentType] # redis stubs omit bytes; KNN vectors are raw bytes at runtime+ )+@classmethod- def _first_hit(cls, search_result: Any) -> _ValkeyCacheHit | None:- docs: Final = getattr(search_result, "docs", [])+ def _first_hit(cls, search_result: object) -> _ValkeyCacheHit | None:+ docs: Final[Sequence[object]] = getattr(search_result, "docs", [])if not docs:return Nonedoc: Final = docs[0]@@@ -282,7 -263,7 +287,7 @@@search_result: Final = self.sync_client.ft(self.index_name).search(self._knn_query(key),-- query_params={"vec": self._embedding_to_bytes(embedding)},++ query_params={"vec": self._embedding_to_bytes(embedding)}, # pyright: ignore[reportArgumentType] # redis stubs omit bytes; KNN vectors are raw bytes at runtime)return self._resolve_hit(self._first_hit(search_result), key, **kwargs)except Exception as e:diff --cc litellm/integrations/compression_interception/handler.pyindex 219718f6771,76720682101..1be7a01ba3a--- a/litellm/integrations/compression_interception/handler.py+++ b/litellm/integrations/compression_interception/handler.py@@@ -7,10 -7,7 +7,10 @@@ litellm_content_retrieve tool calls serimport timeimport uuid-from typing import Any, ClassVar, Final, cast+from collections.abc import Mapping, Sequence- from typing import Any, Final, Protocol, cast++from typing import Any, ClassVar, Final, Protocol, cast++from typing_extensions import ReadOnly, TypedDictfrom litellm._logging import verbose_loggerfrom litellm.compression import compressdiff --cc litellm/integrations/custom_logger.pyindex 417edc77e9c,41caf732db0..f177076d8fe--- a/litellm/integrations/custom_logger.py+++ b/litellm/integrations/custom_logger.py@@@ -2,8 -2,8 +2,8 @@@# On success, logs events to Promptlayerimport reimport traceback- from collections.abc import AsyncGenerator, Sequence- from typing import TYPE_CHECKING, Any, Final, Optional-from collections.abc import AsyncGenerator, Mapping++from collections.abc import AsyncGenerator, Mapping, Sequence+ from typing import TYPE_CHECKING, Any, ClassVar, Final, Optionalfrom pydantic import BaseModeldiff --cc litellm/llms/custom_httpx/container_handler.pyindex 343cf043187,91d68aa3bfb..dd20a8c2ed4--- a/litellm/llms/custom_httpx/container_handler.py+++ b/litellm/llms/custom_httpx/container_handler.py@@@ -11,8 -11,6 +11,7 @@@ from pathlib import Patfrom typing import TYPE_CHECKING, Any, Finalimport httpx- from pydantic import BaseModel+from typing_extensions import NotRequired, ReadOnly, TypedDictimport litellmfrom litellm.litellm_core_utils.url_utils import encode_url_path_segment@@@ -34,47 -32,19 +33,51 @@@ if TYPE_CHECKINGfrom litellm.llms.base_llm.containers.transformation import BaseContainerConfig+class EndpointConfig(TypedDict):+ """One endpoint entry of ``litellm/containers/endpoints.json``."""++ name: ReadOnly[str]+ async_name: ReadOnly[str]+ path: ReadOnly[str]+ method: ReadOnly[str]+ path_params: ReadOnly[Sequence[str]]+ query_params: ReadOnly[Sequence[str]]+ response_type: ReadOnly[str]+ is_multipart: NotRequired[ReadOnly[bool]]+ returns_binary: NotRequired[ReadOnly[bool]]+++class EndpointsConfig(TypedDict):+ """The parsed ``litellm/containers/endpoints.json`` document."""++ endpoints: ReadOnly[Sequence[EndpointConfig]]+++class ContainerErrorDetail(TypedDict, total=False):+ """The ``error`` object of a container API error body."""++ message: ReadOnly[str]+++class ContainerResponseBody(TypedDict, total=False):+ """The fields this handler reads off a container API JSON body."""++ error: ReadOnly[ContainerErrorDetail]++++_ContainerResponseModel = ContainerFileListResponse | ContainerFileObject | DeleteContainerFileResponse++# Response type mapping- RESPONSE_TYPES: Final[Mapping[str, type[BaseModel]]] = {-RESPONSE_TYPES: Final[dict[str, type]] = {++RESPONSE_TYPES: Final[Mapping[str, type[_ContainerResponseModel]]] = {"ContainerFileListResponse": ContainerFileListResponse,"ContainerFileObject": ContainerFileObject,"DeleteContainerFileResponse": DeleteContainerFileResponse,}-ContainerEndpointResponse = (- ContainerFileListResponse | ContainerFileObject | DeleteContainerFileResponse | bytes | dict[str, object]-)++ContainerEndpointResponse = _ContainerResponseModel | bytes | ContainerResponseBody+-def _load_endpoints_config() -> dict:+def _load_endpoints_config() -> EndpointsConfig:"""Load the endpoints configuration from JSON file."""config_path: Final = Path(__file__).parent.parent.parent / "containers" / "endpoints.json"with open(config_path) as f:@@@ -90,11 -60,6 +93,11 @@@ def _get_endpoint_config(endpoint_namereturn None- def _response_model(response_type_name: str) -> type[BaseModel] | None:++def _response_model(response_type_name: str) -> type[_ContainerResponseModel] | None:+ """The pydantic model a container endpoint's ``response_type`` names."""+ return RESPONSE_TYPES.get(response_type_name)++def _build_url(api_base: str,path_template: str,@@@ -128,18 -93,67 +131,63 @@@def _build_query_params(- query_param_names: list,- kwargs: dict[str, Any],-) -> dict[str, str]:+ query_param_names: Sequence[str],+ kwargs: Mapping[str, object],+) -> dict[str, object]:"""Build query parameters from kwargs."""- params: Final = {}- for param_name in query_param_names:- value = kwargs.get(param_name)- if value is not None:- params[param_name] = str(value) if not isinstance(value, str) else value- return params+ supplied: Final = ((param_name, kwargs.get(param_name)) for param_name in query_param_names)+ return {name: value if isinstance(value, str) else str(value) for name, value in supplied if value is not None}+ def _error_message_from_response(response: httpx.Response) -> str:+ try:+ body: Final = response.json()+ except ValueError:+ return response.text++ if isinstance(body, dict) and isinstance(body.get("error"), dict):+ message: Final = body["error"].get("message")+ if isinstance(message, str):+ return message++ return response.text+++ def _transform_response(+ response: httpx.Response,+ returns_binary: bool,+ response_type_name: str,+ ) -> ContainerEndpointResponse:+ from litellm.llms.base_llm.chat.transformation import BaseLLMException++ if httpx.codes.is_error(response.status_code):+ raise BaseLLMException(+ status_code=response.status_code,+ message=_error_message_from_response(response),+ headers=dict(response.headers),+ )++ if returns_binary:+ return response.content+- response_json: Final = response.json()++ response_json: Final[ContainerResponseBody] = response.json()+ if "error" in response_json:+ raise BaseLLMException(+ status_code=response.status_code,- message=response_json.get("error", {}).get("message", str(response_json)),++ message=response_json["error"].get("message", str(response_json)),+ headers=dict(response.headers),+ )+- response_type: Final = RESPONSE_TYPES.get(response_type_name)++ response_type: Final = _response_model(response_type_name)+ if response_type:- return response_type(**response_json)++ return response_type.model_validate(response_json)+ return response_json++def _prepare_multipart_file_upload(file: Any,- headers: dict[str, Any],-) -> tuple:+ headers: dict[str, object],+) -> tuple[dict[str, tuple[str, bytes, str]], dict[str, object]]:"""Prepare file and headers for multipart upload.diff --cc litellm/llms/custom_httpx/http_handler.pyindex 52f30e31641,777ab576de2..b6e93f590ca--- a/litellm/llms/custom_httpx/http_handler.py+++ b/litellm/llms/custom_httpx/http_handler.py@@@ -9,7 -9,7 +9,7 @@@ import threadinimport timefrom collections.abc import AsyncIterable, Callable, Iterable, Mappingfrom http.cookiejar import CookieJar, DefaultCookiePolicy- from typing import TYPE_CHECKING, Any, Final, Optional, TypeAlias, TypedDict-from typing import TYPE_CHECKING, Any, ClassVar, Final, Optional, TypeAlias, TypedDict++from typing import TYPE_CHECKING, Any, ClassVar, Final, NoReturn, Optional, TypeAlias, TypedDictimport certifiimport httpx@@@ -447,7 -447,7 +447,7 @@@ def _safe_read_response(response: httpxreturn b""--def _raise_masked_sync_error(e: httpx.HTTPStatusError, stream: bool) -> None:++def _raise_masked_sync_error(e: httpx.HTTPStatusError, stream: bool) -> NoReturn:"""Raise a MaskedHTTPStatusError for sync HTTP handlers."""if stream:try:@@@ -467,7 -467,7 +467,7 @@@raise MaskedHTTPStatusError(e, message=_text, text=_text) from None--async def _raise_masked_async_error(e: httpx.HTTPStatusError, stream: bool) -> None:++async def _raise_masked_async_error(e: httpx.HTTPStatusError, stream: bool) -> NoReturn:"""Raise a MaskedHTTPStatusError for async HTTP handlers."""if stream:try:diff --cc litellm/llms/e2b/sandbox/transformation.pyindex 9cd9ade77a4,9cd9ade77a4..4928ca0c092--- a/litellm/llms/e2b/sandbox/transformation.py+++ b/litellm/llms/e2b/sandbox/transformation.py@@@ -8,7 -8,7 +8,7 @@@ Talks to e2b's REST API directly over h"""import json--from typing import Final, cast++from typing import Finalimport httpx@@@ -68,13 -68,13 +68,10 @@@ class E2BSandboxConfig(BaseSandboxConfiif metadata:body["metadata"] = metadata-- response: Final = cast(-- httpx.Response,-- await self._http(client).post(-- url=f"{base}/sandboxes",-- headers={"X-API-Key": key, "Content-Type": "application/json"},-- json=body,-- ),++ response: Final = await self._http(client).post(++ url=f"{base}/sandboxes",++ headers={"X-API-Key": key, "Content-Type": "application/json"},++ json=body,)data: Final = response.json()@@@ -117,14 -117,14 +114,11 @@@headers["E2B-Traffic-Access-Token"] = traffic_tokenurl: Final = f"https://{JUPYTER_PORT}-{handle.id}.{handle.domain}/execute"-- response: Final = cast(-- httpx.Response,-- await self._http(client).post(-- url=url,-- headers=headers,-- json={"code": code, "context_id": None, "env_vars": env_vars},-- stream=True,-- ),++ response: Final = await self._http(client).post(++ url=url,++ headers=headers,++ json={"code": code, "context_id": None, "env_vars": env_vars},++ stream=True,)lines: Final = await self._read_capped_lines(response)return self._parse_lines(lines)@@@ -142,12 -142,12 +136,9 @@@key: Final = api_key or handle._hidden_params.get("api_key") or self.validate_environment()base: Final = api_base or handle._hidden_params.get("api_base") or E2B_API_BASEtry:-- response: Final = cast(-- httpx.Response,-- await self._http(client).delete(-- url=f"{base}/sandboxes/{handle.id}",-- headers={"X-API-Key": key},-- ),++ response: Final = await self._http(client).delete(++ url=f"{base}/sandboxes/{handle.id}",++ headers={"X-API-Key": key},)except httpx.HTTPStatusError as e:if e.response.status_code == 404:diff --cc litellm/llms/infinity/rerank/transformation.pyindex df4adf0c9a2,2526eb3b6a4..e089b3fecbe--- a/litellm/llms/infinity/rerank/transformation.py+++ b/litellm/llms/infinity/rerank/transformation.py@@@ -4,7 -4,7 +4,7 @@@ Transformation logic from Cohere's /v1/Why separate file? Make it easy to see how transformation works"""- from collections.abc import Sequence-from collections.abc import Mapping++from collections.abc import Mapping, Sequencefrom typing import Finalimport httpxdiff --cc litellm/llms/opensandbox/sandbox/transformation.pyindex 49a7fb08c4a,49a7fb08c4a..5126db9bbc9--- a/litellm/llms/opensandbox/sandbox/transformation.py+++ b/litellm/llms/opensandbox/sandbox/transformation.py@@@ -1,7 -1,7 +1,7 @@@import asyncioimport jsonimport time--from typing import Final, cast++from typing import Finalimport httpx@@@ -86,13 -86,13 +86,10 @@@ class OpenSandboxSandboxConfig(BaseSandsecure_access=secure_access,)-- response: Final = cast(-- httpx.Response,-- await self._http(client).post(-- url=f"{base}/sandboxes",-- headers=self._lifecycle_headers(key),-- json=body,-- ),++ response: Final = await self._http(client).post(++ url=f"{base}/sandboxes",++ headers=self._lifecycle_headers(key),++ json=body,)data: Final = response.json()sandbox_id: Final = str(data["id"])@@@ -182,12 -182,12 +179,9 @@@base: Final = str(handle._hidden_params.get("api_base") or self._api_base(api_base))key: Final = self._api_key(api_key=api_key, handle=handle)try:-- response: Final = cast(-- httpx.Response,-- await self._http(client).delete(-- url=f"{base}/sandboxes/{handle.id}",-- headers=self._lifecycle_headers(key),-- ),++ response: Final = await self._http(client).delete(++ url=f"{base}/sandboxes/{handle.id}",++ headers=self._lifecycle_headers(key),)except httpx.HTTPStatusError as e:if e.response.status_code == 404:@@@ -245,12 -245,12 +239,9 @@@) -> None:deadline: Final = time.monotonic() + ready_timeoutwhile True:-- response = cast(-- httpx.Response,-- await self._http(client).get(-- url=f"{api_base}/sandboxes/{sandbox_id}",-- headers=headers,-- ),++ response = await self._http(client).get(++ url=f"{api_base}/sandboxes/{sandbox_id}",++ headers=headers,)data = response.json()state = self._sandbox_state(data)@@@ -306,13 -306,13 +297,10 @@@use_server_proxy: bool,client: AsyncHTTPHandler | None,) -> tuple[str, dict[str, str]]:-- response: Final = cast(-- httpx.Response,-- await self._http(client).get(-- url=f"{api_base}/sandboxes/{sandbox_id}/endpoints/{OPEN_SANDBOX_EXECD_PORT}",-- headers=headers,-- params={"use_server_proxy": use_server_proxy},-- ),++ response: Final = await self._http(client).get(++ url=f"{api_base}/sandboxes/{sandbox_id}/endpoints/{OPEN_SANDBOX_EXECD_PORT}",++ headers=headers,++ params={"use_server_proxy": use_server_proxy},)data: Final = response.json()endpoint: Final = data.get("endpoint")@@@ -329,15 -329,15 +317,12 @@@client: AsyncHTTPHandler | None,) -> list[str]:timeout: Final = httpx.Timeout(connect=30.0, read=None, write=30.0, pool=None)-- response: Final = cast(-- httpx.Response,-- await self._http(client).post(-- url=url,-- headers=headers,-- timeout=timeout,-- json=body,-- stream=True,-- ),++ response: Final = await self._http(client).post(++ url=url,++ headers=headers,++ timeout=timeout,++ json=body,++ stream=True,)return await self._read_capped_lines(response)diff --cc litellm/proxy/_experimental/mcp_server/discoverable_endpoints.pyindex 1ca4c657706,93b85edd88d..55a21a14d64--- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py@@@ -1006,8 -1094,8 +1094,7 @@@ async def exchange_token_with_serverheaders={"Accept": "application/json", **token_request.headers},data=token_data,)-- if response is not None:-- response.raise_for_status()++ response.raise_for_status()except httpx.HTTPStatusError as exc:fault: Final = classify_upstream_token_rejection(exc.response,@@@ -1029,11 -1117,11 +1116,6 @@@)return _bridge_mint_error_response("invalid_refresh")return render_token_fault(fault)-- if response is None:-- raise HTTPException(-- status_code=502,-- detail="MCP upstream token endpoint returned no response",-- )token_response = response.json()# Validate token response against server-configured rules before any storage.@@@ -1444,16 -1534,16 +1528,10 @@@ async def _post_dcr_registrationheaders=headers,json=register_data,)-- if response is not None:-- response.raise_for_status()++ response.raise_for_status()except httpx.HTTPStatusError as exc:status_code, detail = dcr_fault_detail(classify_upstream_dcr_rejection(exc.response, log_context=server_id))raise HTTPException(status_code=status_code, detail=detail) from exc-- if response is None:-- raise HTTPException(-- status_code=502,-- detail="MCP upstream registration endpoint returned no response",-- )return responsediff --cc litellm/proxy/_experimental/mcp_server/outbound_credentials/token_endpoint.pyindex f6d40b82eda,f6d40b82eda..84f714db449--- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_endpoint.py+++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_endpoint.py@@@ -111,9 -111,9 +111,6 @@@ class TokenEndpointClientreturn Error(CredError.of_upstream_unavailable("token exchange failed: token endpoint returned a non-JSON response"))-- if raw is None:-- verbose_proxy_logger.warning("MCP token endpoint %s returned no response", endpoint)-- return Error(CredError.of_upstream_unavailable("token exchange failed: no response from token endpoint"))try:parsed: Final = _TokenEndpointResponse.model_validate(raw)except ValidationError:@@@ -199,7 -199,7 +196,7 @@@ def _cache_ttl_seconds(expires_in: int)--async def _post_form(endpoint: str, data: dict[str, str]) -> object | None:++async def _post_form(endpoint: str, data: dict[str, str]) -> object:# litellm's httpx handler and httpx.Response are only partially typed; the token endpoint# returns a JSON object that `_TokenEndpointResponse` validates, so the untyped boundary is# contained here. A non-2xx raises `httpx.HTTPStatusError`, an unreachable endpoint raises@@@ -208,8 -208,8 +205,6 @@@# each to a CredError.client = get_async_httpx_client(llm_provider=httpxSpecialProvider.MCP) # pyright: ignore[reportUnknownVariableType] # litellm http handler is untypedresponse = await client.post(endpoint, data=data) # pyright: ignore[reportUnknownMemberType,reportUnknownVariableType] # litellm http handler is untyped-- if response is None:-- return Noneresponse.raise_for_status()return response.json() # pyright: ignore[reportAny] # untyped JSON; validated by _TokenEndpointResponse in fetchdiff --cc litellm/proxy/agent_endpoints/agent_registry.pyindex edb945fc674,fa33a307438..9554f3f0c92--- a/litellm/proxy/agent_endpoints/agent_registry.py+++ b/litellm/proxy/agent_endpoints/agent_registry.py@@@ -12,7 -12,7 +12,8 @@@ from litellm.proxy.management_helpers.ohandle_update_object_permission_common,)from litellm.proxy.utils import PrismaClient+from litellm.repositories.base_repository import SupportsModelDump+ from litellm.repositories.prisma_protocols import TableActionsfrom litellm.repositories.table_repositories import AgentsRepository, ObjectPermissionRepositoryfrom litellm.types.agents import AgentConfig, AgentResponse, PatchAgentRequestdiff --cc litellm/proxy/db/routing_prisma_wrapper.pyindex 9cc4369fea6,22fc32a898a..2bb241e4265--- a/litellm/proxy/db/routing_prisma_wrapper.py+++ b/litellm/proxy/db/routing_prisma_wrapper.py@@@ -253,12 -245,12 +253,12 @@@ class RoutingPrismaWrapper)return True- async def _recreate_reader(self, http_client: Any | None = None) -> None:+ async def _recreate_reader(self, http_client: object | None = None) -> None:"""Resolve the reader URL and recreate its Prisma client.- IAM-enabled readers regenerate their token (host/port/user came from- the parsed reader URL at construction time). Non-IAM readers reuse- the URL stored in `DATABASE_URL_READ_REPLICA`.+ Token-authenticated readers regenerate their token (host/port/user came+ from the parsed reader URL at construction time). Password-authenticated+ readers reuse the URL stored in `DATABASE_URL_READ_REPLICA`."""if self._reader.iam_token_db_auth:new_reader_url: Final = self._reader.get_rds_iam_token()diff --cc litellm/proxy/guardrails/guardrail_hooks/compresr/compresr.pyindex 37e4c72bf96,37e4c72bf96..866ca2ec803--- a/litellm/proxy/guardrails/guardrail_hooks/compresr/compresr.py+++ b/litellm/proxy/guardrails/guardrail_hooks/compresr/compresr.py@@@ -748,7 -748,7 +748,7 @@@ class CompresrGuardrail(CustomGuardrail}try:-- raw_response: HttpxResponse | None = await self.async_handler.post( # pyright: ignore[reportUnknownMemberType] # AsyncHTTPHandler.post is untyped++ raw_response: HttpxResponse = await self.async_handler.post( # pyright: ignore[reportUnknownMemberType] # AsyncHTTPHandler.post is untypedurl=url,json=payload,headers=self._request_headers(),@@@ -778,11 -778,11 +778,11 @@@{"detail": str(e)},)return None-- if raw_response is None or not 200 <= raw_response.status_code < 300:++ if not 200 <= raw_response.status_code < 300:self._handle_compress_failure("Compresr compression service returned an error",{-- "status_code": getattr(raw_response, "status_code", None),++ "status_code": raw_response.status_code,"body": _safe_response_text(raw_response),},)diff --cc litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.pyindex 8bfd5cca58a,84c6b220e62..d8c41152205--- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py+++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py@@@ -428,7 -429,7 +429,7 @@@ class HeadroomGuardrail(CustomGuardrailpayload["model"] = modeltry:-- raw_response: HttpxResponse | None = await self.async_handler.post( # pyright: ignore[reportUnknownMemberType]++ raw_response: HttpxResponse = await self.async_handler.post( # pyright: ignore[reportUnknownMemberType]url=f"{self.headroom_api_base}/v1/compress",json=payload,headers=self._request_headers(),@@@ -453,16 -454,16 +454,6 @@@False,{},)-- if raw_response is None:-- return (-- self._handle_compress_failure(-- messages,-- "Headroom compression service returned no response",-- {},-- ),-- False,-- {},-- )response: Final[HttpxResponse] = raw_responseif response.status_code != 200:@@@ -575,7 -576,7 +566,7 @@@params["query"] = querytry:-- raw_response: HttpxResponse | None = await self.async_handler.get( # pyright: ignore[reportUnknownMemberType]++ raw_response: HttpxResponse = await self.async_handler.get( # pyright: ignore[reportUnknownMemberType]url=f"{self.headroom_api_base}/v1/retrieve/{hash_value}",params=params,headers=self._request_headers(),@@@ -584,7 -585,7 +575,7 @@@verbose_proxy_logger.warning("Headroom: retrieve failed for hash=%s: %s", hash_value, e)return f"[Headroom: retrieval failed for hash={hash_value}]"-- if raw_response is None or raw_response.status_code == 404:++ if raw_response.status_code == 404:return f"[Headroom: hash={hash_value} not found or expired]"if raw_response.status_code != 200:diff --cc litellm/proxy/guardrails/guardrail_hooks/repelloai/repelloai.pyindex 5f73a169215,5f73a169215..d842a9b9b6a--- a/litellm/proxy/guardrails/guardrail_hooks/repelloai/repelloai.py+++ b/litellm/proxy/guardrails/guardrail_hooks/repelloai/repelloai.py@@@ -197,14 -197,14 +197,11 @@@ class RepelloAIGuardrail(CustomGuardrairepelloai_response: RepelloAIAnalyzeResponse | None = Nonetry:verbose_proxy_logger.debug("RepelloAI Argus request: %s", request)-- raw_response: HttpxResponse | None = await self.async_handler.post( # pyright: ignore[reportUnknownMemberType]++ response: Final[HttpxResponse] = await self.async_handler.post( # pyright: ignore[reportUnknownMemberType]url=endpoint,headers={"X-API-Key": self.repelloai_api_key},json=request,)-- if raw_response is None:-- raise ValueError("RepelloAI Argus returned no response")-- response: Final[HttpxResponse] = raw_responseself._raise_for_config_error(response)response.raise_for_status()try:diff --cc litellm/proxy/management_endpoints/jwt_key_mapping_endpoints.pyindex 7b45afa0ad2,9f561eadfbd..ccfd5338ec4--- a/litellm/proxy/management_endpoints/jwt_key_mapping_endpoints.py+++ b/litellm/proxy/management_endpoints/jwt_key_mapping_endpoints.py@@@ -172,8 -118,13 +172,11 @@@ async def update_jwt_key_mappingcache_key = f"jwt_key_mapping:{old_mapping.jwt_claim_name}:{old_mapping.jwt_claim_value}"await user_api_key_cache.async_delete_cache(cache_key)- updated_mapping: Final = await JWTKeyMappingRepository(prisma_client).table.update(- where={"id": data.id}, data=update_data- )+ updated_mapping: Final = await _mapping_table(prisma_client).update(where={"id": data.id}, data=update_data)+ if updated_mapping is None:+ raise HTTPException(status_code=404, detail="Mapping not found")+# Invalidate new cache key if claim fields changedcache_key = f"jwt_key_mapping:{updated_mapping.jwt_claim_name}:{updated_mapping.jwt_claim_value}"await user_api_key_cache.async_delete_cache(cache_key)diff --cc litellm/repositories/team_repository.pyindex 68490797348,cffa08ce7e0..5ff07d76b5d--- a/litellm/repositories/team_repository.py+++ b/litellm/repositories/team_repository.py@@@ -3,10 -3,9 +3,9 @@@ Team repository for database operation"""import json-from collections.abc import Mapping+from collections.abc import Mapping, Sequence- from contextlib import AbstractAsyncContextManagerfrom datetime import datetime- from typing import TYPE_CHECKING, Any, Final, Protocol-from typing import TYPE_CHECKING, Final++from typing import TYPE_CHECKING, Final, Protocolfrom pydantic import TypeAdapter@@@ -20,39 -19,8 +19,27 @@@ from litellm.repositories.prisma_protocif TYPE_CHECKING:from prisma import Prisma--- class _TeamTables(Protocol):- """The Prisma tables this repository reaches, on the client or inside a transaction."""-- litellm_teamtable: PrismaCrudActions- litellm_deletedteamtable: PrismaCrudActions+ from prisma import models as prisma_models++class _TeamArrays(Protocol):+ """The string array columns of a team row, which the domain model leaves untyped."""++ @property+ def members(self) -> Sequence[str]: ...++ @property+ def admins(self) -> Sequence[str]: ...++ @property+ def models(self) -> Sequence[str]: ...+++def _team_arrays(team: LiteLLM_TeamTable) -> _TeamArrays:+ """View a team's untyped list columns as sequences of ids."""+ return team++- class _TeamDatabase(_TeamTables, Protocol):- """The Prisma client surface used for team reads, writes, and archival transactions."""-- def tx(self) -> AbstractAsyncContextManager[_TeamTables]: ...--_MEMBERS_WITH_ROLES_ADAPTER: Final = TypeAdapter(list[Member])_JSON_ENCODED_TEAM_FIELDS: Final = ("metadata",diff --cc ruff-strict-budget.jsonindex ceaf1ec504f,0418eeaac8f..e1ffc03ae7c--- a/ruff-strict-budget.json+++ b/ruff-strict-budget.json@@@ -1,21 -1,21 +1,21 @@@{"ANN001": {- "limit": 3012- "limit": 3014++ "limit": 2990},"ANN002": {"limit": 71},"ANN003": {- "limit": 818- "limit": 827++ "limit": 800},"ANN201": {- "limit": 2014- "limit": 2011++ "limit": 2005},"ANN202": {- "limit": 851- "limit": 847++ "limit": 848},"ANN204": {- "limit": 707- "limit": 706++ "limit": 695},"ANN205": {"limit": 112@@@ -24,7 -24,7 +24,7 @@@"limit": 133},"ANN401": {- "limit": 1061- "limit": 1153++ "limit": 790},"ASYNC230": {"limit": 11@@@ -198,7 -195,7 +198,7 @@@"limit": 22},"SIM101": {- "limit": 57- "limit": 58++ "limit": 55},"SIM102": {"limit": 317@@@ -234,7 -231,7 +234,7 @@@"limit": 5},"TID251": {- "limit": 1202- "limit": 1201++ "limit": 1170},"TRY002": {"limit": 524@@@ -249,7 -246,7 +249,7 @@@"limit": 113},"TRY300": {- "limit": 858- "limit": 859++ "limit": 856},"UP028": {"limit": 2diff --cc tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_endpoint.pyindex f100bd56f8f,f100bd56f8f..5f277db2f72--- a/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_endpoint.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/outbound_credentials/test_token_endpoint.py@@@ -224,20 -224,20 +224,6 @@@ async def test_fetch_invalid_json_maps_assert "idp.example.com" not in result.error.summary--async def test_fetch_none_response_is_upstream_unavailable():-- with patch(_PATCH_TARGET, return_value=_client(None)):-- result = await TokenEndpointClient().fetch(-- _ENDPOINT,-- _CLIENT_ID,-- {"grant_type": "g"},-- ClientSecretAuth(client_secret=SecretStr("s")),-- )---- assert isinstance(result, Error)-- assert result.error.tag == "upstream_unavailable"----@pytest.mark.asyncioasync def test_fetch_missing_access_token_is_upstream_unavailable():bad = MagicMock()@@@ -275,21 -275,21 +261,6 @@@ async def test_fetch_http_error_does_noassert "idp.example.com" not in result.error.summary--async def test_fetch_none_response_does_not_leak_endpoint_url():-- with patch(_PATCH_TARGET, return_value=_client(None)):-- result = await TokenEndpointClient().fetch(-- _ENDPOINT,-- _CLIENT_ID,-- {"grant_type": "g"},-- ClientSecretAuth(client_secret=SecretStr("s")),-- )---- assert isinstance(result, Error)-- assert _ENDPOINT not in result.error.summary-- assert "idp.example.com" not in result.error.summary----@pytest.mark.asyncioasync def test_fetch_missing_access_token_does_not_leak_endpoint_url():bad = MagicMock()diff --cc type-discipline-budget.jsonindex 890184fad78,a7dec330a26..51cc0a4d8d1--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@@ -1,9 -1,9 +1,9 @@@{"LIT001": {- "limit": 22728- "limit": 22727++ "limit": 22518},"LIT002": {- "limit": 26860- "limit": 26873++ "limit": 26823},"LIT003": {"limit": 269@@@ -15,7 -15,7 +15,7 @@@"limit": 0},"LIT006": {- "limit": 1066- "limit": 1065++ "limit": 1049},"LIT007": {"limit": 0@@@ -27,12 -27,12 +27,12 @@@"limit": 0},"LIT010": {- "limit": 16673- "limit": 16616++ "limit": 16611},"LIT011": {- "limit": 5586- "limit": 5583++ "limit": 5580},"LIT012": {- "limit": 4512- "limit": 4509++ "limit": 4491}}