Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Merge remote-tracking branch 'origin/main' into litellm_decrease_anys_opus5_r5

mateo-berric62c187054d9
diff --cc litellm/integrations/otel/model/metadata.py
index 0de25b3f875,dd4247ad3d0..ad513968b45
--- a/litellm/integrations/otel/model/metadata.py
+++ b/litellm/integrations/otel/model/metadata.py
@@@ -103,11 -107,13 +107,13 @@@ class RequestIdentity
guardrail, or service span is created — so the whole request's spans
inherit identity, not just the LLM-call span. Metadata sub-keys use the
``user_api_key_*`` names that ``baggage.DEFAULT_BAGGAGE_METADATA_KEYS``
- promotes.
+ promotes; ``request_metadata`` (the caller's ``requester_metadata``
+ snapshot) is flattened to dotted keys so ``requester_metadata.<key>``
+ resolves too.
"""
- get: Final = lambda name: getattr(auth, name, None) # noqa: E731
+ get: Final[Callable[[str], object]] = lambda name: getattr(auth, name, None) # noqa: E731
- metadata: Final = {
- meta_key: str(value)
+ auth_meta: Final = tuple(
+ (meta_key, str(value))
for meta_key, attr in (
("user_api_key_user_id", "user_id"),
("user_api_key_org_id", "org_id"),
@@@ -217,10 -225,10 +225,10 @@@ class LLMCallEvent
# needs to be reasonable for a span that never gets closed (a leak).
provisional_span_name: str
time_to_first_chunk_seconds: float | None
- trace_name: str | None
+ trace: TraceControls
@classmethod
- def from_dict(cls, kwargs: Mapping[str, Any]) -> LLMCallEvent:
+ def from_dict(cls, kwargs: Mapping[str, object]) -> LLMCallEvent:
raw_payload: Final = kwargs.get("standard_logging_object")
payload: Final = cast("StandardLoggingPayload", raw_payload) if raw_payload else None
operation: Final = resolve_operation(as_str(kwargs.get("call_type")))
diff --cc litellm/litellm_core_utils/coroutine_checker.py
index a5d4f8b968f,7b9a650c66b..99ba74dbabf
--- a/litellm/litellm_core_utils/coroutine_checker.py
+++ b/litellm/litellm_core_utils/coroutine_checker.py
@@@ -33,10 -33,10 +33,10 @@@ class CoroutineChecker
pass
# Determine target - optimized path for common cases
- target = callback
+ target: object = callback
if not inspect.isfunction(target) and not inspect.ismethod(target):
try:
- call_attr: Final[object] = getattr(target, "__call__", None)
- call_attr: Final = getattr(target, "__call__", None) # noqa: B004 # value unwrap so iscoroutinefunction sees through functors
++ call_attr: Final[object] = getattr(target, "__call__", None) # noqa: B004 # value unwrap so iscoroutinefunction sees through functors
if call_attr is not None:
target = call_attr
except Exception:
diff --cc litellm/litellm_core_utils/exception_mapping_utils.py
index 92f07057da5,61e2698dd6f..425714d730f
--- a/litellm/litellm_core_utils/exception_mapping_utils.py
+++ b/litellm/litellm_core_utils/exception_mapping_utils.py
@@@ -1,7 -2,9 +2,9 @@@ import inspec
import json
import re
import traceback
+ from collections.abc import Mapping
+ from types import MappingProxyType
-from typing import Any, Final, Protocol, cast
+from typing import Final, Protocol, cast
import httpx
@@@ -202,8 -205,13 +205,13 @@@ def _get_response_headers(original_exce
return _response_headers
+ def _accepted_init_kwargs(exception_class: type[Exception], candidates: Mapping[str, object]) -> Mapping[str, object]:
+ accepted: Final = inspect.signature(exception_class).parameters
+ return MappingProxyType({name: value for name, value in candidates.items() if name in accepted})
+
+
def extract_and_raise_litellm_exception(
- response: Any | None,
+ response: object | None,
error_str: str,
model: str,
custom_llm_provider: str,
diff --cc litellm/litellm_core_utils/llm_cost_calc/utils.py
index ff076f5255c,e24fa004448..c60e3089816
--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py
+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py
@@@ -6,9 -6,11 +6,11 @@@ from collections.abc import Mapping, Se
from dataclasses import dataclass
from datetime import datetime, timezone, tzinfo
from types import MappingProxyType
-from typing import Any, Final, Literal, TypedDict, cast
+from typing import Final, Literal, TypedDict, cast
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+ from typing_extensions import ReadOnly
+
import litellm
from litellm._internal_context import current_billing_time
from litellm._logging import verbose_logger
diff --cc litellm/litellm_core_utils/llm_response_utils/response_metadata.py
index d279fb9e259,93701b3c1e7..4a3c8de78c5
--- a/litellm/litellm_core_utils/llm_response_utils/response_metadata.py
+++ b/litellm/litellm_core_utils/llm_response_utils/response_metadata.py
@@@ -1,6 -1,7 +1,7 @@@
import datetime
from collections.abc import Mapping
+ from functools import reduce
-from typing import Any, Final
+from typing import Final
import httpx
diff --cc litellm/litellm_core_utils/sensitive_data_masker.py
index 811be0ee7b8,b7bd0a1498b..b83ecc6929b
--- a/litellm/litellm_core_utils/sensitive_data_masker.py
+++ b/litellm/litellm_core_utils/sensitive_data_masker.py
@@@ -179,26 -187,42 +187,42 @@@ def mask_credentials_in_payload(data: o
Sensitive-key detection is delegated to the shared
:class:`SensitiveDataMasker` so pattern updates stay in one place.
"""
- return _walk_payload(data, key_is_sensitive=False, depth=0)
-
-
- def _walk_payload(node: object, key_is_sensitive: bool, depth: int) -> object:
- if depth >= DEFAULT_MAX_RECURSE_DEPTH_SENSITIVE_DATA_MASKER:
- return node
- if isinstance(node, Mapping):
- return {k: _walk_payload(v, _default_masker.is_sensitive_key(k), depth + 1) for k, v in node.items()}
- if isinstance(node, list):
- return [_walk_payload(item, key_is_sensitive, depth + 1) for item in node]
- if isinstance(node, tuple):
- return tuple(_walk_payload(item, key_is_sensitive, depth + 1) for item in node)
- if isinstance(node, BaseModel):
- return _walk_payload(node.model_dump(), key_is_sensitive, depth)
- if key_is_sensitive and isinstance(node, str) and node:
- return _default_masker._mask_value(node)
- return node
+ return _PayloadWalker().walk(data, key_is_sensitive=False, depth=0)
+
+
+ @dataclass(frozen=True, slots=True)
+ class _PayloadWalker:
+ _memo: dict[tuple[int, bool], tuple[object, object]] = field( # mutable-ok: memo of one walk, pins each keyed node
+ default_factory=dict
+ )
+
+ def walk(self, node: object, key_is_sensitive: bool, depth: int) -> object:
+ if not isinstance(node, (Mapping, list, tuple, BaseModel)):
+ return _default_masker._mask_value(node) if key_is_sensitive and isinstance(node, str) and node else node
+ if depth >= DEFAULT_MAX_RECURSE_DEPTH_SENSITIVE_DATA_MASKER:
+ return REDACTED
+ memo_key: Final = (id(node), key_is_sensitive and not isinstance(node, Mapping))
+ cached: Final = self._memo.get(memo_key)
+ if cached is not None:
+ return cached[1]
+ self._memo[memo_key] = (node, REDACTED)
+ rebuilt: Final = self._rebuild(node, key_is_sensitive, depth)
+ self._memo[memo_key] = (node, rebuilt)
+ return rebuilt
+
+ def _rebuild(
+ self, node: Mapping[str, object] | Sequence[object] | BaseModel, key_is_sensitive: bool, depth: int
+ ) -> object:
+ if isinstance(node, BaseModel):
+ return self.walk(node.model_dump(), key_is_sensitive, depth)
+ if isinstance(node, Mapping):
+ return {k: self.walk(v, _default_masker.is_sensitive_key(k), depth + 1) for k, v in node.items()}
+ if isinstance(node, tuple):
+ return tuple(self.walk(item, key_is_sensitive, depth + 1) for item in node)
+ return [self.walk(item, key_is_sensitive, depth + 1) for item in node]
-def mask_sensitive_keys(data: dict[str, Any], sensitive_fields: set[str]) -> dict[str, Any]:
+def mask_sensitive_keys(data: Mapping[str, object], sensitive_fields: set[str]) -> dict[str, object]:
"""Return a new dict with values masked for keys listed in ``sensitive_fields``.
Unlike :meth:`SensitiveDataMasker.mask_dict`, this does exact key-name
diff --cc litellm/llms/anthropic/common_utils.py
index 7ec15ebd1f4,98e2f6d5bde..c6015e7884e
--- a/litellm/llms/anthropic/common_utils.py
+++ b/litellm/llms/anthropic/common_utils.py
@@@ -7,10 -7,10 +7,10 @@@ import r
from collections.abc import Mapping, MutableMapping, Sequence
from datetime import datetime, timezone
from types import MappingProxyType
-from typing import Any, Final, Literal
+from typing import Any, Final, Literal, TypeVar
import httpx
- from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError
+ from pydantic import BaseModel, ConfigDict, StrictBool, TypeAdapter, ValidationError
import litellm
from litellm.constants import (
diff --cc litellm/llms/bedrock_mantle/responses/transformation.py
index d8356fa9ee4,86e20e31d7f..b04029e4c74
--- a/litellm/llms/bedrock_mantle/responses/transformation.py
+++ b/litellm/llms/bedrock_mantle/responses/transformation.py
@@@ -16,8 -16,8 +16,8 @@@ BaseAWSLLM._sign_request after the requ
"""
import json
-from collections.abc import Mapping
-from typing import Any, Final, cast # noqa: TID251 # map_openai_params returns the filtered params as a bare dict
+from collections.abc import Mapping, Sequence
- from typing import Final
++from typing import Final, cast # noqa: TID251 # map_openai_params returns the filtered params as a bare dict
import httpx
from typing_extensions import ReadOnly, TypedDict
diff --cc litellm/llms/openai/chat/guardrail_translation/handler.py
index 665215303d9,2b895049743..fa5512e7bfe
--- a/litellm/llms/openai/chat/guardrail_translation/handler.py
+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py
@@@ -17,7 -17,8 +17,8 @@@ This pattern can be replicated for othe
import json
import time
import uuid
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
+ from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, Union, cast
from typing_extensions import NotRequired, ReadOnly, TypedDict
diff --cc litellm/llms/vertex_ai/rerank/transformation.py
index 2b1ed3a29a8,b0c6add69fd..dce4d2f2a87
--- a/litellm/llms/vertex_ai/rerank/transformation.py
+++ b/litellm/llms/vertex_ai/rerank/transformation.py
@@@ -4,8 -4,10 +4,10 @@@ Translates from Cohere's `/v1/rerank` i
Why separate file? Make it easy to see how transformation works
"""
+ import math
+ import uuid
from collections.abc import Mapping
-from typing import Any, Final
+from typing import Final
import httpx
diff --cc litellm/proxy/common_utils/reset_budget_job.py
index 3da5c3af5d0,343461fa105..3efc189a475
--- a/litellm/proxy/common_utils/reset_budget_job.py
+++ b/litellm/proxy/common_utils/reset_budget_job.py
@@@ -48,7 -49,8 +49,8 @@@ from litellm.proxy.db.db_transaction_qu
from litellm.proxy.db.exception_handler import call_with_db_reconnect_retry
from litellm.proxy.utils import PrismaClient, ProxyLogging
from litellm.repositories.organization_repository import OrganizationRepository
-from litellm.repositories.prisma_protocols import SpendLinkedTable
+from litellm.repositories.prisma_protocols import PrismaBatch, SpendLinkedTable
+ from litellm.repositories.project_repository import ProjectRepository
from litellm.repositories.table_repositories import (
EndUserRepository,
ModelAccessGroupBudgetRepository,
@@@ -863,18 -958,18 +963,18 @@@ class ResetBudgetJob
reason="reset_budget_write_keys_failure",
)
- async def _write_key_reset_updates_once(self, updated_keys: list[LiteLLM_VerificationToken]) -> None:
+ async def _write_key_reset_updates_once(self, updated_keys: Sequence[_RowReset[LiteLLM_VerificationToken]]) -> None:
- async with spend_reset_unit_of_work(self.prisma_client.db.batch_) as uow:
+ async with spend_reset_unit_of_work(self._new_batch) as uow:
for k in updated_keys:
- if k.token is None:
+ if k.row.token is None:
continue
uow.keys.queue_spend_reset(
- token=k.token,
- budget_reset_at=k.budget_reset_at,
- spend_decrement=k.max_budget if (k.spend or 0.0) > 0.0 else None,
+ token=k.row.token,
+ budget_reset_at=k.row.budget_reset_at,
+ spend_decrement=k.spend_decrement,
)
- async def _write_user_reset_updates(self, updated_users: list[LiteLLM_UserTable]) -> None:
+ async def _write_user_reset_updates(self, updated_users: Sequence[_RowReset[LiteLLM_UserTable]]) -> None:
"""
Write per-row {spend, budget_reset_at} updates for users.
@@@ -887,16 -982,16 +987,16 @@@
reason="reset_budget_write_users_failure",
)
- async def _write_user_reset_updates_once(self, updated_users: list[LiteLLM_UserTable]) -> None:
+ async def _write_user_reset_updates_once(self, updated_users: Sequence[_RowReset[LiteLLM_UserTable]]) -> None:
- async with spend_reset_unit_of_work(self.prisma_client.db.batch_) as uow:
+ async with spend_reset_unit_of_work(self._new_batch) as uow:
for u in updated_users:
uow.users.queue_spend_reset(
- user_id=u.user_id,
- budget_reset_at=u.budget_reset_at,
- spend_decrement=u.max_budget if (u.spend or 0.0) > 0.0 else None,
+ user_id=u.row.user_id,
+ budget_reset_at=u.row.budget_reset_at,
+ spend_decrement=u.spend_decrement,
)
- async def _write_team_reset_updates(self, updated_teams: list[LiteLLM_TeamTable]) -> None:
+ async def _write_team_reset_updates(self, updated_teams: Sequence[_RowReset[LiteLLM_TeamTable]]) -> None:
"""
Write per-row {spend, budget_reset_at} updates for teams.
@@@ -909,13 -1004,13 +1009,13 @@@
reason="reset_budget_write_teams_failure",
)
- async def _write_team_reset_updates_once(self, updated_teams: list[LiteLLM_TeamTable]) -> None:
+ async def _write_team_reset_updates_once(self, updated_teams: Sequence[_RowReset[LiteLLM_TeamTable]]) -> None:
- async with spend_reset_unit_of_work(self.prisma_client.db.batch_) as uow:
+ async with spend_reset_unit_of_work(self._new_batch) as uow:
for t in updated_teams:
uow.teams.queue_spend_reset(
- team_id=t.team_id,
- budget_reset_at=t.budget_reset_at,
- spend_decrement=t.max_budget if (t.spend or 0.0) > 0.0 else None,
+ team_id=t.row.team_id,
+ budget_reset_at=t.row.budget_reset_at,
+ spend_decrement=t.spend_decrement,
)
def _emit_phase_failure(
diff --cc litellm/proxy/db/db_spend_update_writer.py
index 19af995932a,0c88cc23042..0516f5460a7
--- a/litellm/proxy/db/db_spend_update_writer.py
+++ b/litellm/proxy/db/db_spend_update_writer.py
@@@ -12,10 -12,14 +12,14 @@@ import o
import random
import time
import traceback
- from collections.abc import Mapping, Sequence
+ from collections.abc import Callable, Mapping, Sequence
from datetime import datetime, timedelta, timezone
from types import MappingProxyType
- from typing import TYPE_CHECKING, Any, Final, Literal, Protocol, TypeAlias, cast, overload
-from typing import TYPE_CHECKING, Any, Final, Literal, Protocol, TypeVar, cast, overload
++from typing import TYPE_CHECKING, Any, Final, Literal, Protocol, TypeAlias, TypeVar, cast, overload
+ from urllib.parse import quote, unquote
+
+ from pydantic import TypeAdapter
+ from typing_extensions import LiteralString, ReadOnly, TypedDict
import litellm
from litellm._logging import verbose_proxy_logger
@@@ -115,20 -136,6 +136,24 @@@ class _SpendBatch(Protocol)
litellm_modelaccessgroupbudgettable: BatchTable
- _EntitySpendTable: TypeAlias = Literal["litellm_tagtable", "litellm_agentstable", "litellm_modelaccessgroupbudgettable"]
++_EntitySpendTable: TypeAlias = Literal[
++ "litellm_tagtable", "litellm_agentstable", "litellm_modelaccessgroupbudgettable", "litellm_projecttable"
++]
+
+
+def _entity_spend_table(batcher: _SpendBatch, table_accessor: _EntitySpendTable) -> BatchTable:
+ """The batch table an entity type's spend increments are written to."""
+ match table_accessor:
+ case "litellm_tagtable":
+ return batcher.litellm_tagtable
+ case "litellm_agentstable":
+ return batcher.litellm_agentstable
+ case "litellm_modelaccessgroupbudgettable":
+ return batcher.litellm_modelaccessgroupbudgettable
++ case "litellm_projecttable":
++ return batcher.litellm_projecttable
+
+
class _SpendBatchManager(Protocol):
async def __aenter__(self) -> _SpendBatch: ...
diff --cc litellm/proxy/db/exception_handler.py
index 6e2052ce3a4,9146f234570..f25c2787252
--- a/litellm/proxy/db/exception_handler.py
+++ b/litellm/proxy/db/exception_handler.py
@@@ -1,6 -1,9 +1,9 @@@
+ import re
from collections.abc import Awaitable, Callable, Iterator
-from typing import Any, Final, TypeVar
+from typing import Final, Protocol, TypeVar
+ from pydantic import TypeAdapter, ValidationError
+
from litellm._logging import verbose_proxy_logger
from litellm.proxy._types import (
DB_CONNECTION_ERROR_TYPES,
diff --cc litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.py
index 806ab5161e8,8eac6b2ee53..efec15144b8
--- a/litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/llm_as_a_judge/__init__.py
@@@ -1,11 -1,13 +1,13 @@@
- """LLM-as-a-Judge guardrail: uses an LLM to score responses against weighted criteria."""
+ """LLM-as-a-Judge guardrail: uses an LLM to score requests or responses against weighted criteria."""
- from collections.abc import Callable, Sequence
+ from collections.abc import Callable, Mapping, Sequence
from datetime import datetime
+ from types import MappingProxyType
-from typing import TYPE_CHECKING, Any, Final, Generic, Literal, Optional, TypeVar
+from typing import TYPE_CHECKING, Final, Generic, Literal, Optional, TypeVar
from fastapi import HTTPException
+ from pydantic import BaseModel, ConfigDict, ValidationError
-from typing_extensions import NotRequired, ReadOnly, TypedDict
+from typing_extensions import NotRequired, ReadOnly, TypedDict, Unpack
import litellm
from litellm._logging import verbose_logger
@@@ -106,25 -177,8 +177,25 @@@ def _build_judge_prompt
)
+class _CustomGuardrailOptions(TypedDict, total=False):
+ """The ``CustomGuardrail`` options this guardrail accepts and forwards untouched."""
+
+ mask_request_content: ReadOnly[bool]
+ mask_response_content: ReadOnly[bool]
+ violation_message_template: ReadOnly[str | None]
+ end_session_after_n_fails: ReadOnly[int | None]
+ on_violation: ReadOnly[str | None]
+ realtime_violation_message: ReadOnly[str | None]
+ on_sensitive_data: ReadOnly[str | None]
+ sensitive_data_route_to_model: ReadOnly[str | None]
+ sticky_session_routing: ReadOnly[bool]
+ run_in_parallel: ReadOnly[bool]
+ scan_raw_request: ReadOnly[bool]
+ only_scan_new_messages: ReadOnly[bool]
+
+
class LLMAsAJudgeGuardrail(CustomGuardrail):
- """Post-call guardrail that judges response quality via an LLM."""
+ """Guardrail that judges request (pre_call/during_call) or response (post_call) quality via an LLM."""
def __init__(
self,
@@@ -133,18 -187,11 +204,11 @@@
criteria: Sequence[JudgeCriterion],
overall_threshold: float = 80.0,
on_failure: Literal["block", "log"] = "block",
- event_hook: GuardrailEventHooks | list[GuardrailEventHooks] | None = None,
+ event_hook: JudgeModeParam = None,
default_on: bool = False,
router_provider: "Callable[[], Router | None] | None" = None,
- **kwargs: Any,
+ **kwargs: Unpack[_CustomGuardrailOptions],
) -> None:
- _event_hook: GuardrailEventHooks | list[GuardrailEventHooks] | None = None
- if event_hook is not None:
- if isinstance(event_hook, list):
- _event_hook = [GuardrailEventHooks(h) if isinstance(h, str) else h for h in event_hook]
- else:
- _event_hook = GuardrailEventHooks(event_hook) if isinstance(event_hook, str) else event_hook
-
super().__init__(
guardrail_name=guardrail_name,
supported_event_hooks=list(self.get_supported_event_hooks()),
diff --cc litellm/proxy/guardrails/usage_endpoints.py
index 3f7c36bbbf2,556b6a4e919..fc237bd55c4
--- a/litellm/proxy/guardrails/usage_endpoints.py
+++ b/litellm/proxy/guardrails/usage_endpoints.py
@@@ -42,10 -42,9 +42,10 @@@ if TYPE_CHECKING
router: Final = APIRouter()
_EMPTY_UNITS: Final[Mapping[str, int]] = MappingProxyType({})
- _ACTION_SEVERITY: Final[Mapping[str, int]] = MappingProxyType({"passed": 0, "flagged": 1, "blocked": 2})
+ _ACTION_SEVERITY: Final[Mapping[str, int]] = MappingProxyType({"not_run": 0, "passed": 1, "flagged": 2, "blocked": 3})
_T = TypeVar("_T")
+_MetricsRowT = TypeVar("_MetricsRowT", bound="_DailyMetricsRow")
_USAGE_MAX_RANGE_DAYS: Final = 366
diff --cc litellm/proxy/hooks/proxy_track_cost_callback.py
index e1fc87d8ed9,b38fb856215..08e8e4f8c10
--- a/litellm/proxy/hooks/proxy_track_cost_callback.py
+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py
@@@ -1,8 -1,8 +1,8 @@@
import asyncio
import traceback
- from collections.abc import Callable, Sequence
+ from collections.abc import Callable, Mapping, Sequence
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final, cast
+from typing import TYPE_CHECKING, Any, Final, Protocol, cast
import litellm
from litellm._logging import verbose_proxy_logger
diff --cc litellm/proxy/ocr_endpoints/endpoints.py
index 8170c95e3e6,981581919e4..0f997fcd745
--- a/litellm/proxy/ocr_endpoints/endpoints.py
+++ b/litellm/proxy/ocr_endpoints/endpoints.py
@@@ -28,10 -29,18 +29,18 @@@ def _build_document_from_upload
filename: str | None,
content_type: str | None,
) -> dict[str, str]:
- return convert_upload_to_url_document(file_content, filename, content_type)
+ supplied_mime: Final = content_type.split(";")[0].strip() if content_type else None
+ mime_type: Final = (
+ get_mime_type(filename)
+ if filename and (not supplied_mime or supplied_mime == "application/octet-stream")
+ else supplied_mime
+ )
+ return convert_file_document_to_url_document(
+ {"type": "file", "file": file_content, "mime_type": mime_type or "application/octet-stream"}
+ )
-def _with_request_format(data: Mapping[str, Any], request: Request) -> Mapping[str, Any]:
+def _with_request_format(data: Mapping[str, object], request: Request) -> Mapping[str, object]:
"""
Resolve the requested response format from the body or the `x-req-format` header.
diff --cc litellm/proxy/openai_files_endpoints/storage_backend_service.py
index 0407499cbcc,66dbcd87c0b..53f48d93aa2
--- a/litellm/proxy/openai_files_endpoints/storage_backend_service.py
+++ b/litellm/proxy/openai_files_endpoints/storage_backend_service.py
@@@ -7,6 -7,7 +7,7 @@@ storage backends (e.g., Azure Blob Stor
import base64
import time
-from collections.abc import Mapping, Sequence
++from collections.abc import Sequence
from typing import Any, Final, cast
from litellm._logging import verbose_proxy_logger
@@@ -14,9 -16,9 +16,9 @@@ from litellm.llms.base_llm.files.storag
from litellm.llms.base_llm.files.storage_backend_factory import get_storage_backend
from litellm.llms.base_llm.files.transformation import BaseFileEndpoints
from litellm.proxy._types import ProxyException, UserAPIKeyAuth
- from litellm.proxy.utils import ProxyLogging
+ from litellm.proxy.utils import PrismaClient, ProxyLogging
from litellm.types.llms.openai import OpenAIFileObject, OpenAIFilesPurpose
-from litellm.types.utils import SpecialEnums
+from litellm.types.utils import ExtractedFileData, SpecialEnums
class StorageBackendFileService:
@@@ -32,9 -34,9 +34,9 @@@
@staticmethod
async def upload_file_to_storage_backend(
- file_data: Mapping[str, Any],
+ file_data: ExtractedFileData,
target_storage: str,
- target_model_names: list[str],
+ target_model_names: Sequence[str],
purpose: OpenAIFilesPurpose,
proxy_logging_obj: ProxyLogging,
user_api_key_dict: UserAPIKeyAuth,
@@@ -162,8 -183,8 +183,8 @@@
@staticmethod
def _create_unified_file_id(
- file_type: str,
+ file_type: str | None,
- target_model_names: list[str],
+ target_model_names: Sequence[str],
file_id: str,
) -> str:
"""
@@@ -192,8 -213,8 +213,8 @@@
@staticmethod
async def _store_in_managed_files(
file_object: OpenAIFileObject,
- file_data: Mapping[str, Any],
+ file_data: ExtractedFileData,
- target_model_names: list[str],
+ target_model_names: Sequence[str],
target_storage: str,
storage_url: str,
proxy_logging_obj: ProxyLogging,
diff --cc litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py
index ce44596c19c,cd226e80c6e..48c1ced47ae
--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py
+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/vertex_passthrough_logging_handler.py
@@@ -48,8 -52,75 +53,73 @@@ else
PassThroughEndpointLogging = Any
LiteLLMBatch = Any
-EndpointType = Any
-
+ _VERTEX_INTERACTIONS_PATH: Final = re.compile(r"/projects/[^/]+/locations/[^/]+/interactions/?$")
+ _INTERACTIONS_RESPONSE_BODY: Final = TypeAdapter(dict[str, object])
+
+
+ def _interactions_model(
+ response_body: Mapping[str, object],
+ request_body: Mapping[str, object] | None,
+ ) -> str | None:
+ response_model: Final = response_body.get("model")
+ if isinstance(response_model, str) and response_model:
+ return response_model
+ request_model: Final = (request_body or {}).get("model")
+ if isinstance(request_model, str) and request_model:
+ return request_model
+ return None
+
class VertexPassthroughLoggingHandler:
+ @staticmethod
+ def is_interactions_route(url_route: str) -> bool:
+ return urlparse(url_route).path.rstrip("/").endswith("/interactions")
+
+ @staticmethod
+ def is_vertex_interactions_route(url_route: str) -> bool:
+ return _VERTEX_INTERACTIONS_PATH.search(urlparse(url_route).path) is not None
+
+ @staticmethod
+ def interactions_passthrough_handler(
+ httpx_response: httpx.Response,
+ request_body: Mapping[str, object] | None,
+ logging_obj: LiteLLMLoggingObj,
+ kwargs: dict[str, object],
+ start_time: datetime,
+ end_time: datetime,
+ custom_llm_provider: Literal["vertex_ai", "gemini"],
+ vertex_location: str | None,
+ ) -> PassThroughEndpointLoggingTypedDict:
+ response_body: Final = _INTERACTIONS_RESPONSE_BODY.validate_python(httpx_response.json())
+ usage_object: Final = response_body.get("usage")
+ model: Final = _interactions_model(response_body, request_body)
+ if model is None or not InteractionsUsageObjectTransformation.is_interactions_usage_object(usage_object):
+ return {"result": None, "kwargs": kwargs}
+
+ litellm_model_response: Final = ModelResponse(
+ model=model,
+ usage=InteractionsUsageObjectTransformation.transform_interactions_usage_object(
+ cast(Mapping[str, Any], usage_object)
+ ),
+ )
+ logging_obj.custom_llm_provider = custom_llm_provider
+ logging_kwargs: Final = (
+ VertexPassthroughLoggingHandler._create_vertex_response_logging_payload_for_generate_content(
+ litellm_model_response=litellm_model_response,
+ model=model,
+ kwargs=kwargs,
+ start_time=start_time,
+ end_time=end_time,
+ logging_obj=logging_obj,
+ custom_llm_provider=custom_llm_provider,
+ vertex_location=vertex_location,
+ )
+ )
+ return {
+ "result": litellm_model_response,
+ "kwargs": {**logging_kwargs, "custom_llm_provider": custom_llm_provider},
+ }
+
@staticmethod
def vertex_passthrough_handler(
httpx_response: httpx.Response,
diff --cc litellm/realtime_api/main.py
index 9b52e9614e8,0e83edab5e1..acc42c44c04
--- a/litellm/realtime_api/main.py
+++ b/litellm/realtime_api/main.py
@@@ -53,7 -55,18 +55,18 @@@ bedrock_realtime: Final = BedrockRealti
xai_realtime: Final = XAIRealtime()
vertex_llm_base: Final = VertexBase()
base_llm_http_handler = BaseLLMHTTPHandler()
-_EMPTY_MODEL_PARAMS: Final[Mapping[str, Any]] = MappingProxyType({})
+_EMPTY_MODEL_PARAMS: Final[Mapping[str, object]] = MappingProxyType({})
+ _EMPTY_AUTH_HEADERS: Final[Mapping[str, str]] = MappingProxyType({})
+
+
-def _model_params_with_stored_credentials(model_params: Mapping[str, Any]) -> Mapping[str, Any]:
++def _model_params_with_stored_credentials(model_params: Mapping[str, object]) -> Mapping[str, object]:
+ credential_name: Final = model_params.get("litellm_credential_name")
+ credential_values: Final = (
+ CredentialAccessor.get_credential_values(credential_name)
+ if isinstance(credential_name, str)
+ else _EMPTY_MODEL_PARAMS
+ )
+ return MappingProxyType({**credential_values, **model_params})
def _with_resolved_session_model(session: dict[str, object], model_name: str) -> dict[str, object]:
diff --cc litellm/router_strategy/complexity_router/complexity_router.py
index eea0b2ec564,64f3600af18..27affc09337
--- a/litellm/router_strategy/complexity_router/complexity_router.py
+++ b/litellm/router_strategy/complexity_router/complexity_router.py
@@@ -1165,9 -1286,10 +1286,10 @@@ class ComplexityRouter(CustomLogger)
self,
model_name: str,
litellm_router_instance: Router,
- complexity_router_config: dict[str, Any] | None = None,
+ complexity_router_config: Mapping[str, object] | None = None,
default_model: str | None = None,
derive_savings_baseline: bool = True,
+ jev_client: JevClassifierClient | None = None,
):
"""
Initialize ComplexityRouter.
@@@ -2262,15 -2827,22 +2827,22 @@@
async def _pick_model_for_tier(
self,
tier: ComplexityTier | str,
- raw_messages: list[dict[str, Any]] | None,
- resolved_messages: list[dict[str, Any]] | None,
+ raw_messages: list[dict[str, object]] | None,
+ resolved_messages: list[dict[str, object]] | None,
request_kwargs: dict,
allowed_models: tuple[str, ...] | None = None,
+ retained_pin: _SessionAffinityPin | None = None,
) -> str:
if not self.config.plugins:
- if allowed_models is not None:
- return self._pick_from_tier_value(allowed_models, _tier_name(tier))
- return self.get_model_for_tier(tier)
+ candidates: Final = (
+ allowed_models if allowed_models is not None else tuple(self._tier_pools().get(_tier_name(tier), ()))
+ )
+ selected: Final = (
+ self._pick_from_tier_value(allowed_models, _tier_name(tier))
+ if allowed_models is not None
+ else self.get_model_for_tier(tier)
+ )
+ return await self._pin_model_for_tier(tier, selected, candidates, request_kwargs, retained_pin)
from litellm.types.router import RoutingContext
diff --cc litellm/types/guardrails.py
index 5d8a3334d7e,172edf136fd..579a3f6322f
--- a/litellm/types/guardrails.py
+++ b/litellm/types/guardrails.py
@@@ -2,12 -2,15 +2,15 @@@ from collections.abc import Mappin
from datetime import datetime
from enum import Enum
from types import MappingProxyType
-from typing import Any, Final, Literal
+from typing import Final, Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
-from typing_extensions import Required, TypedDict
+from typing_extensions import ReadOnly, Required, TypedDict
from litellm.constants import BEDROCK_APPLY_GUARDRAIL_CHUNK_BUDGET_CHARS
+ from litellm.types.proxy.guardrails.guardrail_hooks.agent_365 import (
+ Agent365GuardrailConfigModel,
+ )
from litellm.types.proxy.guardrails.guardrail_hooks.akto import (
AktoConfigModel,
)