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(proxy): use return value from CustomLogger.async_post_call_success_hook (#19670)
michelligabriele558f01e84824
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 5dcb0339739..83296927a76 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -1793,9 +1793,11 @@ class ProxyLogging:#################################################################for callback in other_callbacks:- await callback.async_post_call_success_hook(+ callback_response = await callback.async_post_call_success_hook(user_api_key_dict=user_api_key_dict, data=data, response=response)+ if callback_response is not None:+ response = callback_responseexcept Exception as e:raise ereturn response@@ -1852,16 +1854,14 @@ class ProxyLogging:complete_response = str_so_far + response_strelse:complete_response = response_str- potential_error_response = (+ callback_response = (await _callback.async_post_call_streaming_hook(user_api_key_dict=user_api_key_dict,response=complete_response,))- if isinstance(- potential_error_response, str- ) and potential_error_response.startswith("data: "):- return potential_error_response+ if callback_response is not None:+ response = callback_responseexcept Exception as e:raise ereturn responsediff --git a/tests/test_litellm/proxy/hooks/test_post_call_streaming_hook_integration.py b/tests/test_litellm/proxy/hooks/test_post_call_streaming_hook_integration.pynew file mode 100644index 00000000000..3bc111ef142--- /dev/null+++ b/tests/test_litellm/proxy/hooks/test_post_call_streaming_hook_integration.py@@ -0,0 +1,273 @@+"""+Integration tests for async_post_call_streaming_hook.++Tests verify that the streaming hook can transform streaming responses sent to clients.+"""++import os+import sys+import pytest+from typing import Any+from unittest.mock import patch, MagicMock++sys.path.insert(0, os.path.abspath("../../../.."))++import litellm+from litellm.integrations.custom_logger import CustomLogger+from litellm.proxy._types import UserAPIKeyAuth+from litellm.types.utils import ModelResponseStream, StreamingChoices, Delta+++class StreamingResponseTransformerLogger(CustomLogger):+ """Logger that transforms streaming responses"""++ def __init__(self, transform_content: str = None):+ self.called = False+ self.transform_content = transform_content+ self.received_response = None++ async def async_post_call_streaming_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ response: str,+ ) -> Any:+ self.called = True+ self.received_response = response+ if self.transform_content is not None:+ return self.transform_content+ return None+++async def test_streaming_hook_transforms_response():+ """+ Test that async_post_call_streaming_hook can transform streaming responses.+ """+ transformer = StreamingResponseTransformerLogger(transform_content="Modified streaming response")++ with patch("litellm.callbacks", [transformer]):+ from litellm.proxy.utils import ProxyLogging+ from litellm.caching.caching import DualCache++ proxy_logging = ProxyLogging(user_api_key_cache=DualCache())++ # Create a mock streaming response+ original_response = ModelResponseStream(+ id="original-stream",+ choices=[+ StreamingChoices(+ delta=Delta(content="Original content", role="assistant"),+ index=0,+ )+ ],+ model="test-model",+ )++ data = {"model": "test-model"}+ user_api_key_dict = UserAPIKeyAuth(api_key="test-key")++ # Call the hook+ result = await proxy_logging.async_post_call_streaming_hook(+ data=data,+ response=original_response,+ user_api_key_dict=user_api_key_dict,+ )++ # Verify hook was called+ assert transformer.called is True++ # Verify transformed response is returned+ assert result == "Modified streaming response"+++async def test_streaming_hook_returns_none_keeps_original():+ """+ Test that hook returning None keeps the original response.+ """++ class NoOpLogger(CustomLogger):+ def __init__(self):+ self.called = False++ async def async_post_call_streaming_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ response: str,+ ):+ self.called = True+ return None++ logger = NoOpLogger()++ with patch("litellm.callbacks", [logger]):+ from litellm.proxy.utils import ProxyLogging+ from litellm.caching.caching import DualCache++ proxy_logging = ProxyLogging(user_api_key_cache=DualCache())++ original_response = ModelResponseStream(+ id="original-stream",+ choices=[+ StreamingChoices(+ delta=Delta(content="Original content", role="assistant"),+ index=0,+ )+ ],+ model="test-model",+ )++ data = {"model": "test-model"}+ user_api_key_dict = UserAPIKeyAuth(api_key="test-key")++ result = await proxy_logging.async_post_call_streaming_hook(+ data=data,+ response=original_response,+ user_api_key_dict=user_api_key_dict,+ )++ # Should return original response object+ assert result.id == "original-stream"+ assert logger.called is True+++async def test_streaming_hook_works_with_sse_format():+ """+ Test that hook works with SSE-formatted strings (data: prefix).+ This was the only supported format before the fix.+ """+ transformer = StreamingResponseTransformerLogger(+ transform_content="data: {\"error\": \"custom error\"}\n\n"+ )++ with patch("litellm.callbacks", [transformer]):+ from litellm.proxy.utils import ProxyLogging+ from litellm.caching.caching import DualCache++ proxy_logging = ProxyLogging(user_api_key_cache=DualCache())++ original_response = ModelResponseStream(+ id="original-stream",+ choices=[+ StreamingChoices(+ delta=Delta(content="Original content", role="assistant"),+ index=0,+ )+ ],+ model="test-model",+ )++ data = {"model": "test-model"}+ user_api_key_dict = UserAPIKeyAuth(api_key="test-key")++ result = await proxy_logging.async_post_call_streaming_hook(+ data=data,+ response=original_response,+ user_api_key_dict=user_api_key_dict,+ )++ # Verify SSE-formatted response is returned+ assert result == "data: {\"error\": \"custom error\"}\n\n"+++async def test_streaming_hook_chains_multiple_callbacks():+ """+ Test that multiple callbacks can chain modifications.+ """++ class AppendLogger(CustomLogger):+ def __init__(self, suffix: str):+ self.suffix = suffix+ self.called = False++ async def async_post_call_streaming_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ response: str,+ ) -> str:+ self.called = True+ # Note: response here is the complete_response string, not the chunk+ return f"[{self.suffix}]"++ callback1 = AppendLogger("CB1")+ callback2 = AppendLogger("CB2")++ with patch("litellm.callbacks", [callback1, callback2]):+ from litellm.proxy.utils import ProxyLogging+ from litellm.caching.caching import DualCache++ proxy_logging = ProxyLogging(user_api_key_cache=DualCache())++ original_response = ModelResponseStream(+ id="original-stream",+ choices=[+ StreamingChoices(+ delta=Delta(content="Hello", role="assistant"),+ index=0,+ )+ ],+ model="test-model",+ )++ data = {"model": "test-model"}+ user_api_key_dict = UserAPIKeyAuth(api_key="test-key")++ result = await proxy_logging.async_post_call_streaming_hook(+ data=data,+ response=original_response,+ user_api_key_dict=user_api_key_dict,+ )++ # Both callbacks should have been called+ assert callback1.called is True+ assert callback2.called is True++ # Last callback's result should be used+ assert result == "[CB2]"+++async def test_streaming_hook_handles_exceptions():+ """+ Test that hook exceptions are propagated.+ """++ class FailingLogger(CustomLogger):+ async def async_post_call_streaming_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ response: str,+ ):+ raise RuntimeError("Streaming hook crashed!")++ logger = FailingLogger()++ with patch("litellm.callbacks", [logger]):+ from litellm.proxy.utils import ProxyLogging+ from litellm.caching.caching import DualCache++ proxy_logging = ProxyLogging(user_api_key_cache=DualCache())++ original_response = ModelResponseStream(+ id="original-stream",+ choices=[+ StreamingChoices(+ delta=Delta(content="Hello", role="assistant"),+ index=0,+ )+ ],+ model="test-model",+ )++ data = {"model": "test-model"}+ user_api_key_dict = UserAPIKeyAuth(api_key="test-key")++ # Exception should be propagated+ with pytest.raises(RuntimeError, match="Streaming hook crashed!"):+ await proxy_logging.async_post_call_streaming_hook(+ data=data,+ response=original_response,+ user_api_key_dict=user_api_key_dict,+ )diff --git a/tests/test_litellm/proxy/hooks/test_post_call_success_hook_integration.py b/tests/test_litellm/proxy/hooks/test_post_call_success_hook_integration.pynew file mode 100644index 00000000000..870286f5382--- /dev/null+++ b/tests/test_litellm/proxy/hooks/test_post_call_success_hook_integration.py@@ -0,0 +1,260 @@+"""+Integration tests for async_post_call_success_hook.++Tests verify that the success hook can transform responses sent to clients.+This mirrors the behavior of CustomGuardrail hooks and streaming iterator hooks.+"""++import os+import sys+import pytest+from typing import Any+from unittest.mock import patch, MagicMock++sys.path.insert(0, os.path.abspath("../../../.."))++import litellm+from litellm.integrations.custom_logger import CustomLogger+from litellm.proxy._types import UserAPIKeyAuth+from litellm.types.utils import ModelResponse, Choices, Message, Usage+++class ResponseTransformerLogger(CustomLogger):+ """Logger that transforms successful responses"""++ def __init__(self, transform_content: str = None):+ self.called = False+ self.transform_content = transform_content++ async def async_post_call_success_hook(+ self,+ data: dict,+ user_api_key_dict: UserAPIKeyAuth,+ response: Any,+ ) -> Any:+ self.called = True+ if self.transform_content is not None:+ # Create a modified response with custom content+ return {+ "id": "transformed-response",+ "choices": [+ {+ "message": {"content": self.transform_content, "role": "assistant"},+ "index": 0,+ }+ ],+ "model": "test-model",+ "custom_field": "added_by_hook",+ }+ return response+++async def test_success_hook_transforms_response():+ """+ Test that async_post_call_success_hook can transform successful responses.+ """+ transformer = ResponseTransformerLogger(transform_content="Modified response")++ with patch("litellm.callbacks", [transformer]):+ from litellm.proxy.utils import ProxyLogging+ from litellm.caching.caching import DualCache++ proxy_logging = ProxyLogging(user_api_key_cache=DualCache())++ # Create a mock response+ original_response = ModelResponse(+ id="original-response",+ choices=[+ Choices(+ message=Message(content="Original content", role="assistant"),+ index=0,+ finish_reason="stop",+ )+ ],+ model="test-model",+ usage=Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),+ )++ data = {"model": "test-model"}+ user_api_key_dict = UserAPIKeyAuth(api_key="test-key")++ # Call the hook+ result = await proxy_logging.post_call_success_hook(+ data=data,+ response=original_response,+ user_api_key_dict=user_api_key_dict,+ )++ # Verify hook was called+ assert transformer.called is True++ # Verify transformed response is returned+ assert result is not None+ assert result["id"] == "transformed-response"+ assert result["choices"][0]["message"]["content"] == "Modified response"+ assert result["custom_field"] == "added_by_hook"+++async def test_success_hook_returns_none_keeps_original():+ """+ Test that hook returning None keeps the original response.+ """++ class NoOpLogger(CustomLogger):+ def __init__(self):+ self.called = False++ async def async_post_call_success_hook(self, *args, **kwargs):+ self.called = True+ return None++ logger = NoOpLogger()++ with patch("litellm.callbacks", [logger]):+ from litellm.proxy.utils import ProxyLogging+ from litellm.caching.caching import DualCache++ proxy_logging = ProxyLogging(user_api_key_cache=DualCache())++ original_response = ModelResponse(+ id="original-response",+ choices=[+ Choices(+ message=Message(content="Original content", role="assistant"),+ index=0,+ finish_reason="stop",+ )+ ],+ model="test-model",+ usage=Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),+ )++ data = {"model": "test-model"}+ user_api_key_dict = UserAPIKeyAuth(api_key="test-key")++ result = await proxy_logging.post_call_success_hook(+ data=data,+ response=original_response,+ user_api_key_dict=user_api_key_dict,+ )++ # Should return original response+ assert result.id == "original-response"+ assert logger.called is True+++async def test_success_hook_chains_multiple_callbacks():+ """+ Test that multiple callbacks can chain modifications.+ """++ class AddFieldLogger(CustomLogger):+ def __init__(self, field_name: str, field_value: Any):+ self.field_name = field_name+ self.field_value = field_value+ self.called = False++ async def async_post_call_success_hook(+ self,+ data: dict,+ user_api_key_dict: UserAPIKeyAuth,+ response: Any,+ ) -> Any:+ self.called = True+ # Convert response to dict if needed+ if hasattr(response, "model_dump"):+ resp_dict = response.model_dump()+ elif hasattr(response, "dict"):+ resp_dict = response.dict()+ elif isinstance(response, dict):+ resp_dict = response.copy()+ else:+ resp_dict = {}++ resp_dict[self.field_name] = self.field_value+ return resp_dict++ callback1 = AddFieldLogger("field1", "value1")+ callback2 = AddFieldLogger("field2", "value2")++ with patch("litellm.callbacks", [callback1, callback2]):+ from litellm.proxy.utils import ProxyLogging+ from litellm.caching.caching import DualCache++ proxy_logging = ProxyLogging(user_api_key_cache=DualCache())++ original_response = ModelResponse(+ id="original-response",+ choices=[+ Choices(+ message=Message(content="Original content", role="assistant"),+ index=0,+ finish_reason="stop",+ )+ ],+ model="test-model",+ usage=Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),+ )++ data = {"model": "test-model"}+ user_api_key_dict = UserAPIKeyAuth(api_key="test-key")++ result = await proxy_logging.post_call_success_hook(+ data=data,+ response=original_response,+ user_api_key_dict=user_api_key_dict,+ )++ # Both callbacks should have been called+ assert callback1.called is True+ assert callback2.called is True++ # Both fields should be present (chained modifications)+ assert result["field1"] == "value1"+ assert result["field2"] == "value2"+++async def test_success_hook_handles_exceptions():+ """+ Test that hook exceptions are propagated (not silently swallowed).+ """++ class FailingLogger(CustomLogger):+ async def async_post_call_success_hook(self, *args, **kwargs):+ raise RuntimeError("Hook crashed!")++ logger = FailingLogger()++ with patch("litellm.callbacks", [logger]):+ from litellm.proxy.utils import ProxyLogging+ from litellm.caching.caching import DualCache++ proxy_logging = ProxyLogging(user_api_key_cache=DualCache())++ original_response = ModelResponse(+ id="original-response",+ choices=[+ Choices(+ message=Message(content="Original content", role="assistant"),+ index=0,+ finish_reason="stop",+ )+ ],+ model="test-model",+ usage=Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),+ )++ data = {"model": "test-model"}+ user_api_key_dict = UserAPIKeyAuth(api_key="test-key")++ # Exception should be propagated+ with pytest.raises(RuntimeError, match="Hook crashed!"):+ await proxy_logging.post_call_success_hook(+ data=data,+ response=original_response,+ user_api_key_dict=user_api_key_dict,+ )