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 litellm_internal_staging into litellm_anthropic_messages_response_cache
shivama09551a71a24
diff --cc litellm/caching/caching.pyindex 88a5e08604e,b696de068d9..f0fb91b987f--- a/litellm/caching/caching.py+++ b/litellm/caching/caching.py@@@ -55,52 -55,64 +55,51 @@@ class CacheMode(str, Enum)class Cache:def __init__(self,- type: Optional[LiteLLMCacheType] = LiteLLMCacheType.LOCAL,- mode: Optional[- CacheMode- ] = CacheMode.default_on, # when default_on cache is always on, when default_off cache is opt in- host: Optional[str] = None,- port: Optional[str] = None,- password: Optional[str] = None,- namespace: Optional[str] = None,- ttl: Optional[float] = None,- default_in_memory_ttl: Optional[float] = None,- default_in_redis_ttl: Optional[float] = None,- similarity_threshold: Optional[float] = None,+ type: LiteLLMCacheType | None = LiteLLMCacheType.LOCAL,+ mode: CacheMode+ | None = CacheMode.default_on, # when default_on cache is always on, when default_off cache is opt in+ host: str | None = None,+ port: str | None = None,+ password: str | None = None,+ namespace: str | None = None,+ ttl: float | None = None,+ default_in_memory_ttl: float | None = None,+ default_in_redis_ttl: float | None = None,+ similarity_threshold: float | None = None,- supported_call_types: list[CachingSupportedCallTypes] | None = [- "completion",- "acompletion",- "embedding",- "aembedding",- "atranscription",- "transcription",- "atext_completion",- "text_completion",- "arerank",- "rerank",- "responses",- "aresponses",- ],+ supported_call_types: list[CachingSupportedCallTypes] | None = list(DEFAULT_CACHING_SUPPORTED_CALL_TYPES),# s3 Bucket, boto3 configuration- azure_account_url: Optional[str] = None,- azure_blob_container: Optional[str] = None,- s3_bucket_name: Optional[str] = None,- s3_region_name: Optional[str] = None,- s3_api_version: Optional[str] = None,- s3_use_ssl: Optional[bool] = True,- s3_verify: Optional[Union[bool, str]] = None,- s3_endpoint_url: Optional[str] = None,- s3_aws_access_key_id: Optional[str] = None,- s3_aws_secret_access_key: Optional[str] = None,- s3_aws_session_token: Optional[str] = None,- s3_config: Optional[Any] = None,- s3_path: Optional[str] = None,- gcs_bucket_name: Optional[str] = None,- gcs_path_service_account: Optional[str] = None,- gcs_path: Optional[str] = None,+ azure_account_url: str | None = None,+ azure_blob_container: str | None = None,+ s3_bucket_name: str | None = None,+ s3_region_name: str | None = None,+ s3_api_version: str | None = None,+ s3_use_ssl: bool | None = True,+ s3_verify: bool | str | None = None,+ s3_endpoint_url: str | None = None,+ s3_aws_access_key_id: str | None = None,+ s3_aws_secret_access_key: str | None = None,+ s3_aws_session_token: str | None = None,+ s3_config: Any | None = None,+ s3_path: str | None = None,+ gcs_bucket_name: str | None = None,+ gcs_path_service_account: str | None = None,+ gcs_path: str | None = None,redis_semantic_cache_embedding_model: str = "text-embedding-ada-002",- redis_semantic_cache_index_name: Optional[str] = None,+ redis_semantic_cache_index_name: str | None = None,valkey_semantic_cache_embedding_model: str = "text-embedding-ada-002",valkey_semantic_cache_index_name: str | None = None,- redis_flush_size: Optional[int] = None,- redis_startup_nodes: Optional[List] = None,- disk_cache_dir: Optional[str] = None,- qdrant_api_base: Optional[str] = None,- qdrant_api_key: Optional[str] = None,- qdrant_collection_name: Optional[str] = None,- qdrant_quantization_config: Optional[str] = None,+ redis_flush_size: int | None = None,+ redis_startup_nodes: list | None = None,+ disk_cache_dir: str | None = None,+ qdrant_api_base: str | None = None,+ qdrant_api_key: str | None = None,+ qdrant_collection_name: str | None = None,+ qdrant_quantization_config: str | None = None,qdrant_semantic_cache_embedding_model: str = "text-embedding-ada-002",- qdrant_semantic_cache_vector_size: Optional[int] = None,+ qdrant_semantic_cache_vector_size: int | None = None,# GCP IAM authentication parameters- gcp_service_account: Optional[str] = None,- gcp_ssl_ca_certs: Optional[str] = None,+ gcp_service_account: str | None = None,+ gcp_ssl_ca_certs: str | None = None,**kwargs,):"""@@@ -913,11 -923,24 +910,11 @@@def enable_cache(- type: Optional[LiteLLMCacheType] = LiteLLMCacheType.LOCAL,- host: Optional[str] = None,- port: Optional[str] = None,- password: Optional[str] = None,+ type: LiteLLMCacheType | None = LiteLLMCacheType.LOCAL,+ host: str | None = None,+ port: str | None = None,+ password: str | None = None,- supported_call_types: list[CachingSupportedCallTypes] | None = [- "completion",- "acompletion",- "embedding",- "aembedding",- "atranscription",- "transcription",- "atext_completion",- "text_completion",- "arerank",- "rerank",- "responses",- "aresponses",- ],+ supported_call_types: list[CachingSupportedCallTypes] | None = list(DEFAULT_CACHING_SUPPORTED_CALL_TYPES),**kwargs,):"""@@@ -960,11 -983,24 +957,11 @@@def update_cache(- type: Optional[LiteLLMCacheType] = LiteLLMCacheType.LOCAL,- host: Optional[str] = None,- port: Optional[str] = None,- password: Optional[str] = None,+ type: LiteLLMCacheType | None = LiteLLMCacheType.LOCAL,+ host: str | None = None,+ port: str | None = None,+ password: str | None = None,- supported_call_types: list[CachingSupportedCallTypes] | None = [- "completion",- "acompletion",- "embedding",- "aembedding",- "atranscription",- "transcription",- "atext_completion",- "text_completion",- "arerank",- "rerank",- "responses",- "aresponses",- ],+ supported_call_types: list[CachingSupportedCallTypes] | None = list(DEFAULT_CACHING_SUPPORTED_CALL_TYPES),**kwargs,):"""diff --cc litellm/caching/caching_handler.pyindex 70a2e3fd1b2,370b704ac2e..5e1570880ab--- a/litellm/caching/caching_handler.py+++ b/litellm/caching/caching_handler.py@@@ -18,19 -18,8 +18,8 @@@ import asynciimport datetimeimport inspectimport time- from collections.abc import AsyncIterator- from typing import (- TYPE_CHECKING,- Any,- AsyncGenerator,- Callable,- Dict,- Generator,- List,- Optional,- Tuple,- Union,- )-from collections.abc import AsyncGenerator, Callable, Generator-from typing import TYPE_CHECKING, Any, Final, Optional++from collections.abc import AsyncGenerator, AsyncIterator, Callable, Generator++from typing import TYPE_CHECKING, Any, Final, Optional, TypeVarfrom pydantic import BaseModel@@@ -60,10 -49,10 +49,15 @@@ from litellm.types.utils importif TYPE_CHECKING:from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj++ from litellm.llms.anthropic.experimental_pass_through.messages.response_cache import (++ AnthropicMessagesStreamCacheWriter,++ )from litellm.types.utils import PromptTokensDetailsWrapperelse:LiteLLMLoggingObj = Any++_StreamResultT = TypeVar("_StreamResultT")++from litellm.litellm_core_utils.core_helpers import (_get_parent_otel_span_from_kwargs,@@@ -850,23 -835,11 +841,23 @@@ class LLMCachingHandlerresponse_type="audio_transcription",hidden_params=hidden_params,)+ elif (+ call_type == CallTypes.anthropic_messages.value or call_type == CallTypes.aanthropic_messages.value+ ) and isinstance(cached_result, dict):+ from litellm.llms.anthropic.experimental_pass_through.messages.response_cache import (+ convert_cached_anthropic_messages_result,+ )++ cached_result = convert_cached_anthropic_messages_result(+ cached_result=cached_result,+ logging_obj=logging_obj,+ kwargs=kwargs,+ )elif (call_type == "aresponses" or call_type == "responses") and isinstance(cached_result, dict):- use_chat_completion_cache = _is_chat_completion_cached_dict(cached_result)+ use_chat_completion_cache: Final = _is_chat_completion_cached_dict(cached_result)if use_chat_completion_cache:if kwargs.get("stream", False) is True:- bridge_call_type = (+ bridge_call_type: Final = (CallTypes.acompletion.value if call_type == "aresponses" else CallTypes.completion.value)cached_result = self._convert_cached_stream_response(@@@ -1058,24 -1031,6 +1049,26 @@@and (kwargs.get("cache", {}).get("no-store", False) is not True))- def wrap_streaming_result_for_cache(self, result: Any, call_type: str) -> Any:++ def wrap_streaming_result_for_cache(++ self, result: _StreamResultT, call_type: str++ ) -> "_StreamResultT | AnthropicMessagesStreamCacheWriter":+ if call_type not in (+ CallTypes.anthropic_messages.value,+ CallTypes.aanthropic_messages.value,+ ):+ return result+ if litellm.cache is None or not self._should_store_result_in_cache(+ original_function=self.original_function, kwargs=self.request_kwargs+ ):+ return result+ if not isinstance(result, AsyncIterator):+ return result+ from litellm.llms.anthropic.experimental_pass_through.messages.response_cache import (+ AnthropicMessagesStreamCacheWriter,+ )++ return AnthropicMessagesStreamCacheWriter(stream=result, caching_handler=self)+def _is_call_type_supported_by_cache(self,original_function: Callable,diff --cc litellm/litellm_core_utils/model_param_helper.pyindex 7e99e5fc5b2,692e954eadc..3696a328807--- a/litellm/litellm_core_utils/model_param_helper.py+++ b/litellm/litellm_core_utils/model_param_helper.py@@@ -40,11 -39,11 +40,11 @@@ class ModelParamHelperreturn standard_logging_model_parameters@staticmethod- def get_exclude_params_for_model_parameters() -> Set[str]:+ def get_exclude_params_for_model_parameters() -> set[str]:- return set(["messages", "prompt", "input"])+ return set(["messages", "prompt", "input", "system"])@staticmethod- def _get_relevant_args_to_use_for_logging() -> Set[str]:+ def _get_relevant_args_to_use_for_logging() -> set[str]:"""Gets all relevant llm api params besides the ones with prompt content"""@@@ -68,14 -67,13 +68,14 @@@(``_get_relevant_args_to_use_for_logging``). Callers treat the result asread-only."""- chat_completion_kwargs = ModelParamHelper._get_litellm_supported_chat_completion_kwargs()- text_completion_kwargs = ModelParamHelper._get_litellm_supported_text_completion_kwargs()- embedding_kwargs = ModelParamHelper._get_litellm_supported_embedding_kwargs()- transcription_kwargs = ModelParamHelper._get_litellm_supported_transcription_kwargs()- rerank_kwargs = ModelParamHelper._get_litellm_supported_rerank_kwargs()- responses_api_kwargs = ModelParamHelper._get_litellm_supported_responses_api_kwargs()- anthropic_messages_kwargs = ModelParamHelper._get_litellm_supported_anthropic_messages_kwargs()- exclude_kwargs = ModelParamHelper._get_exclude_kwargs()+ chat_completion_kwargs: Final = ModelParamHelper._get_litellm_supported_chat_completion_kwargs()+ text_completion_kwargs: Final = ModelParamHelper._get_litellm_supported_text_completion_kwargs()+ embedding_kwargs: Final = ModelParamHelper._get_litellm_supported_embedding_kwargs()+ transcription_kwargs: Final = ModelParamHelper._get_litellm_supported_transcription_kwargs()+ rerank_kwargs: Final = ModelParamHelper._get_litellm_supported_rerank_kwargs()+ responses_api_kwargs: Final = ModelParamHelper._get_litellm_supported_responses_api_kwargs()++ anthropic_messages_kwargs: Final = ModelParamHelper._get_litellm_supported_anthropic_messages_kwargs()+ exclude_kwargs: Final = ModelParamHelper._get_exclude_kwargs()combined_kwargs = chat_completion_kwargs.union(text_completion_kwargs,@@@ -166,19 -163,12 +166,19 @@@This follows the OpenAI API Spec"""- non_streaming_params: Set[str] = set(getattr(ResponseCreateParamsNonStreaming, "__annotations__", {}).keys())- streaming_params: Set[str] = set(getattr(ResponseCreateParamsStreaming, "__annotations__", {}).keys())+ non_streaming_params: set[str] = set(getattr(ResponseCreateParamsNonStreaming, "__annotations__", {}).keys())+ streaming_params: Final[set[str]] = set(getattr(ResponseCreateParamsStreaming, "__annotations__", {}).keys())return non_streaming_params.union(streaming_params)+ @staticmethod- def _get_litellm_supported_anthropic_messages_kwargs() -> set[str]:++ def _get_litellm_supported_anthropic_messages_kwargs() -> frozenset[str]:+ """+ Get the litellm supported Anthropic /v1/messages kwargs+ """- return set(AnthropicMessagesRequest.__annotations__.keys())++ return frozenset(AnthropicMessagesRequest.__annotations__.keys())+@staticmethod- def _get_exclude_kwargs() -> Set[str]:+ def _get_exclude_kwargs() -> set[str]:"""Get the kwargs to exclude from the cache key"""diff --cc litellm/llms/anthropic/experimental_pass_through/messages/response_cache.pyindex d5b68c99130,00000000000..1bbb1317fd9mode 100644,000000..100644--- a/litellm/llms/anthropic/experimental_pass_through/messages/response_cache.py+++ b/litellm/llms/anthropic/experimental_pass_through/messages/response_cache.py@@@ -1,138 -1,0 +1,143 @@@- from collections.abc import AsyncIterator- from typing import TYPE_CHECKING, Any, cast++from collections.abc import AsyncIterator, Mapping, Sequence++from types import MappingProxyType++from typing import TYPE_CHECKING, Final++import litellm+from litellm._logging import verbose_logger+from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (++ AnthropicMessagesStreamingResponse,+ BaseAnthropicMessagesStreamingIterator,+ _is_message_stop_chunk,+ _is_provider_error_chunk,+ aclose_if_supported,+)- from litellm.types.llms.anthropic_messages.anthropic_response import (- AnthropicMessagesResponse,- )++if TYPE_CHECKING:+ from litellm.caching.caching_handler import LLMCachingHandler+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj- else:- LLMCachingHandler = Any- LiteLLMLoggingObj = Any+- CACHED_STREAM_EVENTS_KEY = "litellm_cached_anthropic_sse_events"++CACHED_STREAM_EVENTS_KEY: Final = "litellm_cached_anthropic_sse_events"++++_EMPTY_MAPPING: Final[Mapping[str, object]] = MappingProxyType({})+++def _decode(chunk: bytes | str) -> str:+ return chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk+++class AnthropicMessagesStreamCacheWriter:+ def __init__(+ self,+ stream: AsyncIterator[bytes | str],+ caching_handler: "LLMCachingHandler",+ ) -> None:+ self.stream = stream+ self.caching_handler = caching_handler- self.collected_events: list[str] = []++ self.collected_events: list[str] = [] # mutable-ok: rebuilding a tuple per SSE chunk is quadratic+ self.saw_message_stop = False+ self.saw_provider_error = False+ self.persisted = False- self._hidden_params: dict[str, Any] = getattr(stream, "_hidden_params", {}) or {}++ self._hidden_params: dict[str, object] = dict( # mutable-ok: callers stamp cache_key in here++ stream._hidden_params if isinstance(stream, AnthropicMessagesStreamingResponse) else _EMPTY_MAPPING++ )++ def __aiter__(self) -> "AnthropicMessagesStreamCacheWriter":+ return self++ async def __anext__(self) -> bytes | str:+ try:- chunk = await self.stream.__anext__()++ chunk: Final = await self.stream.__anext__()+ except StopAsyncIteration:+ await self._persist()+ raise- chunk_bytes = chunk.encode("utf-8") if isinstance(chunk, str) else chunk++ chunk_bytes: Final = chunk.encode("utf-8") if isinstance(chunk, str) else chunk+ self.saw_message_stop = self.saw_message_stop or _is_message_stop_chunk(chunk_bytes)+ self.saw_provider_error = self.saw_provider_error or _is_provider_error_chunk(chunk_bytes)+ self.collected_events.append(_decode(chunk))+ return chunk++ async def aclose(self) -> None:+ await aclose_if_supported(self.stream)++ async def _persist(self) -> None:+ if self.persisted or litellm.cache is None:+ return+ if not self.saw_message_stop or self.saw_provider_error:+ return+ self.persisted = True+- request_kwargs = dict(self.caching_handler.request_kwargs)+ if not self.caching_handler._should_store_result_in_cache(+ original_function=self.caching_handler.original_function,- kwargs=request_kwargs,++ kwargs=self.caching_handler.request_kwargs,+ ):+ return- preset_cache_key = self.caching_handler.preset_cache_key- if preset_cache_key is not None:- request_kwargs["cache_key"] = preset_cache_key++ preset_cache_key: Final = self.caching_handler.preset_cache_key++ cache_key_override: Final[Mapping[str, object]] = (++ MappingProxyType({"cache_key": preset_cache_key}) if preset_cache_key is not None else _EMPTY_MAPPING++ )++ request_kwargs: Final[Mapping[str, object]] = MappingProxyType(++ {**self.caching_handler.request_kwargs, **cache_key_override}++ )++ events: Final = tuple(self.collected_events)++ cached_payload: Final = {CACHED_STREAM_EVENTS_KEY: events} # mutable-ok: cache backends serialize plain dicts++ try:+ await litellm.cache.async_add_cache(- {CACHED_STREAM_EVENTS_KEY: self.collected_events},++ cached_payload,+ dynamic_cache_object=self.caching_handler.dual_cache,+ **request_kwargs,+ )- except Exception as e:++ except Exception as e: # noqa: BLE001 # a cache write must never surface as a client-visible stream error+ verbose_logger.exception("Anthropic Messages stream cache write failed: %s", e)+++class CachedAnthropicMessagesStreamIterator(BaseAnthropicMessagesStreamingIterator):+ def __init__(+ self,- events: list[str],- litellm_logging_obj: LiteLLMLoggingObj,- request_body: dict[str, Any],++ events: Sequence[str],++ litellm_logging_obj: "LiteLLMLoggingObj",++ request_body: Mapping[str, object],+ ) -> None:- super().__init__(litellm_logging_obj=litellm_logging_obj, request_body=request_body)- self.chunks: list[bytes] = [event.encode("utf-8") for event in events]++ body: Final = dict(request_body) # mutable-ok: the base iterator takes a plain dict++ super().__init__(litellm_logging_obj=litellm_logging_obj, request_body=body)++ self.chunks: Final[tuple[bytes, ...]] = tuple(event.encode("utf-8") for event in events)+ self.current_index = 0+ self.logged = False- self._hidden_params: dict[str, Any] = {"cache_hit": True}++ self._hidden_params: dict[str, object] = {"cache_hit": True} # mutable-ok: callers stamp cache_key in here+ litellm_logging_obj.model_call_details["cache_hit"] = True++ def __aiter__(self) -> "CachedAnthropicMessagesStreamIterator":+ return self++ async def __anext__(self) -> bytes:+ if self.current_index >= len(self.chunks):+ if not self.logged:+ self.logged = True- await self._handle_streaming_logging(self.chunks)++ chunks: Final = list(self.chunks) # mutable-ok: the logging handler takes a list++ await self._handle_streaming_logging(chunks)+ raise StopAsyncIteration- chunk = self.chunks[self.current_index]++ chunk: Final = self.chunks[self.current_index]+ self.current_index += 1+ return chunk++- def get_cached_stream_events(cached_result: dict[str, Any]) -> list[str] | None:- events = cached_result.get(CACHED_STREAM_EVENTS_KEY)- if isinstance(events, list):- return [_decode(event) for event in events]++def get_cached_stream_events(cached_result: Mapping[str, object]) -> tuple[str, ...] | None:++ events: Final = cached_result.get(CACHED_STREAM_EVENTS_KEY)++ if isinstance(events, (list, tuple)):++ return tuple(_decode(event) for event in events if isinstance(event, (bytes, str)))+ return None+++def convert_cached_anthropic_messages_result(- cached_result: dict[str, Any],- logging_obj: LiteLLMLoggingObj,- kwargs: dict[str, Any],- ) -> AnthropicMessagesResponse | CachedAnthropicMessagesStreamIterator:- events = get_cached_stream_events(cached_result)- if events is not None:- return CachedAnthropicMessagesStreamIterator(- events=events,- litellm_logging_obj=logging_obj,- request_body=kwargs,- )- return cast( # cast-ok: AnthropicMessagesResponse is a TypedDict; validating would drop provider fields we must replay verbatim- AnthropicMessagesResponse, cached_result++ cached_result: Mapping[str, object],++ logging_obj: "LiteLLMLoggingObj",++ kwargs: Mapping[str, object],++) -> Mapping[str, object] | CachedAnthropicMessagesStreamIterator:++ events: Final = get_cached_stream_events(cached_result)++ if events is None:++ return cached_result++ return CachedAnthropicMessagesStreamIterator(++ events=events,++ litellm_logging_obj=logging_obj,++ request_body=kwargs,+ )diff --cc litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.pyindex 51813983876,9fb967e570f..abfa5d88a5d--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/anthropic_passthrough_logging_handler.py@@@ -255,16 -256,12 +256,16 @@@ class AnthropicPassthroughLoggingHandlelitellm_params=(logging_obj.litellm_params if hasattr(logging_obj, "litellm_params") else None))- response_cost = (- response_cost: Final = litellm.completion_cost(- completion_response=litellm_model_response,- model=model_for_cost,- custom_llm_provider=custom_llm_provider,- custom_pricing=custom_pricing,- router_model_id=router_model_id,++ response_cost: Final = (+ 0.0+ if logging_obj.model_call_details.get("cache_hit") is True+ else litellm.completion_cost(+ completion_response=litellm_model_response,+ model=model_for_cost,+ custom_llm_provider=custom_llm_provider,+ custom_pricing=custom_pricing,+ router_model_id=router_model_id,+ ))kwargs["response_cost"] = response_cost