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
fix(caching): defer streaming cache-hit callbacks for all stream=True
Sameer Kankutee0398cade78a
diff --git a/litellm/caching/caching_handler.py b/litellm/caching/caching_handler.pyindex 02207a207ed..3cf1d911d7f 100644--- a/litellm/caching/caching_handler.py+++ b/litellm/caching/caching_handler.py@@ -85,19 +85,18 @@ class CachingHandlerResponse(BaseModel):in_memory_cache_obj = InMemoryCache()-_RESPONSES_STREAMING_CALLBACK_CALL_TYPES = {- CallTypes.aresponses.value,- CallTypes.responses.value,-}---def _should_defer_streaming_cache_hit_callbacks(- *, call_type: str, kwargs: Dict[str, Any]-) -> bool:- return (- kwargs.get("stream", False) is True- and call_type in _RESPONSES_STREAMING_CALLBACK_CALL_TYPES- )+++def _should_defer_streaming_cache_hit_callbacks(*, kwargs: Dict[str, Any]) -> bool:+ """+ When stream=True, do not run success callbacks at cache-hit time.++ Cached chat/text completion replay uses CustomStreamWrapper; cached Responses+ replay uses CachedResponsesAPIStreamingIterator. Both invoke logging success+ handlers when the stream finishes; firing them here too would double-count+ spend and callback records.+ """+ return kwargs.get("stream", False) is Trueclass LLMCachingHandler:@@ -220,10 +219,7 @@ class LLMCachingHandler:custom_llm_provider=kwargs.get("custom_llm_provider", None),args=args,)- if not _should_defer_streaming_cache_hit_callbacks(- call_type=call_type,- kwargs=kwargs,- ):+ if not _should_defer_streaming_cache_hit_callbacks(kwargs=kwargs):# LOG SUCCESSself._async_log_cache_hit_on_callbacks(logging_obj=logging_obj,@@ -343,10 +339,7 @@ class LLMCachingHandler:is_async=False,)- if not _should_defer_streaming_cache_hit_callbacks(- call_type=call_type,- kwargs=kwargs,- ):+ if not _should_defer_streaming_cache_hit_callbacks(kwargs=kwargs):logging_obj.handle_sync_success_callbacks_for_async_calls(result=cached_result,start_time=start_time,diff --git a/tests/local_testing/test_caching_handler.py b/tests/local_testing/test_caching_handler.pyindex 0ce9938e710..2b6712cbaa3 100644--- a/tests/local_testing/test_caching_handler.py+++ b/tests/local_testing/test_caching_handler.py@@ -891,7 +891,7 @@ def test_sync_get_cache_does_not_eagerly_log_streaming_responses_hits():logging_obj.handle_sync_success_callbacks_for_async_calls.assert_not_called()-def test_sync_get_cache_still_eagerly_logs_streaming_completion_hits():+def test_sync_get_cache_defers_streaming_completion_hit_callbacks():litellm.set_verbose = Truesetup_cache()caching_handler = LLMCachingHandler(@@ -930,42 +930,32 @@ def test_sync_get_cache_still_eagerly_logs_streaming_completion_hits():)assert cached_response.cached_result is not None- logging_obj.handle_sync_success_callbacks_for_async_calls.assert_called_once()+ logging_obj.handle_sync_success_callbacks_for_async_calls.assert_not_called()-def test_should_defer_streaming_cache_hit_callbacks_only_for_responses_streams():- assert (- _should_defer_streaming_cache_hit_callbacks(- call_type=CallTypes.responses.value,- kwargs={"stream": True},- )- is True- )+def test_should_defer_streaming_cache_hit_callbacks_for_any_streaming_request():assert (_should_defer_streaming_cache_hit_callbacks(- call_type=CallTypes.aresponses.value,kwargs={"stream": True},)is True)assert (_should_defer_streaming_cache_hit_callbacks(- call_type=CallTypes.completion.value,- kwargs={"stream": True},+ kwargs={"stream": False},)is False)assert (_should_defer_streaming_cache_hit_callbacks(- call_type=CallTypes.responses.value,- kwargs={"stream": False},+ kwargs={},)is False)@pytest.mark.asyncio-async def test_async_get_cache_still_eagerly_logs_streaming_completion_hits():+async def test_async_get_cache_defers_streaming_completion_hit_callbacks():litellm.set_verbose = Truesetup_cache()caching_handler = LLMCachingHandler(@@ -1009,7 +999,7 @@ async def test_async_get_cache_still_eagerly_logs_streaming_completion_hits():assert cached_response is not Noneassert cached_response.cached_result is not None- caching_handler._async_log_cache_hit_on_callbacks.assert_called_once()+ caching_handler._async_log_cache_hit_on_callbacks.assert_not_called()def test_convert_cached_streaming_responses_result_to_iterator():