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]

[Feat] Add failure logging support for s3 logger (#12299)

Ishaan Jaff3d71b49d11f1
diff --git a/litellm/integrations/s3_v2.py b/litellm/integrations/s3_v2.py
index 121a491cfcf..09a58498e15 100644
--- a/litellm/integrations/s3_v2.py
+++ b/litellm/integrations/s3_v2.py
@@ -2,7 +2,7 @@
s3 Bucket Logging Integration
async_log_success_event: Processes the event, stores it in memory for DEFAULT_S3_FLUSH_INTERVAL_SECONDS seconds or until DEFAULT_S3_BATCH_SIZE and then flushes to s3
-
+async_log_failure_event: Processes the event, stores it in memory for DEFAULT_S3_FLUSH_INTERVAL_SECONDS seconds or until DEFAULT_S3_BATCH_SIZE and then flushes to s3
NOTE 1: S3 does not provide a BATCH PUT API endpoint, so we create tasks to upload each element individually
"""
@@ -197,6 +197,24 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
return
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
+ await self._async_log_event_base(
+ kwargs=kwargs,
+ response_obj=response_obj,
+ start_time=start_time,
+ end_time=end_time,
+ )
+
+ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
+ await self._async_log_event_base(
+ kwargs=kwargs,
+ response_obj=response_obj,
+ start_time=start_time,
+ end_time=end_time,
+ )
+ pass
+
+
+ async def _async_log_event_base(self, kwargs, response_obj, start_time, end_time):
try:
verbose_logger.debug(
f"s3 Logging - Enters logging function for model {kwargs}"
@@ -224,6 +242,7 @@ class S3Logger(CustomBatchLogger, BaseAWSLLM):
verbose_logger.exception(f"s3 Layer Error - {str(e)}")
pass
+
async def async_upload_data_to_s3(
self, batch_logging_element: s3BatchLoggingElement
):
diff --git a/tests/logging_callback_tests/test_amazing_s3_logs.py b/tests/logging_callback_tests/test_amazing_s3_logs.py
index 92993d0d76d..37666d72b79 100644
--- a/tests/logging_callback_tests/test_amazing_s3_logs.py
+++ b/tests/logging_callback_tests/test_amazing_s3_logs.py
@@ -79,6 +79,7 @@ async def test_basic_s3_logging(sync_mode, streaming):
@pytest.mark.parametrize(
"streaming", [(True)]
)
[email protected](retries=3, delay=1)
async def test_basic_s3_v2_logging(streaming):
from blockbuster import BlockBuster
from litellm.integrations.s3_v2 import S3Logger
@@ -127,6 +128,92 @@ async def test_basic_s3_v2_logging(streaming):
s3.delete_object(Bucket="load-testing-oct", Key=key)
[email protected](retries=3, delay=1)
+async def test_basic_s3_v2_logging_failure():
+ """Test that S3 v2 logger makes httpx PUT request when logging failures"""
+ from unittest.mock import AsyncMock, MagicMock, patch
+ from litellm.integrations.s3_v2 import S3Logger
+
+ # Create S3 logger with short flush interval
+ s3_v2_logger = S3Logger(s3_flush_interval=1)
+
+ # Mock the httpx client to capture the PUT request
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.raise_for_status = MagicMock()
+
+ s3_v2_logger.async_httpx_client = AsyncMock()
+ s3_v2_logger.async_httpx_client.put.return_value = mock_response
+
+ # Track the upload method calls
+ original_upload = s3_v2_logger.async_upload_data_to_s3
+ upload_called = False
+
+ async def mock_upload(batch_logging_element):
+ nonlocal upload_called
+ upload_called = True
+ # Mock the upload process but still make the httpx call
+ url = f"https://test-bucket.s3.us-west-2.amazonaws.com/{batch_logging_element.s3_object_key}"
+ headers = {"Content-Type": "application/json"}
+ data = '{"model": "gpt-4o-mini"}'
+
+ # Make the actual httpx call we want to test
+ await s3_v2_logger.async_httpx_client.put(url=url, headers=headers, data=data)
+
+ s3_v2_logger.async_upload_data_to_s3 = mock_upload
+
+ # Configure S3 callback params
+ litellm.callbacks = [s3_v2_logger]
+ litellm.s3_callback_params = {
+ "s3_bucket_name": "test-bucket",
+ "s3_aws_secret_access_key": "test-secret",
+ "s3_aws_access_key_id": "test-key",
+ "s3_region_name": "us-west-2",
+ }
+ litellm.set_verbose = True
+
+ # Trigger a failure by using invalid API key
+ try:
+ response = await litellm.acompletion(
+ model="gpt-4o-mini",
+ api_key="invalid-api-key",
+ messages=[{"role": "user", "content": "This is a test"}],
+ )
+ except Exception as e:
+ print(f"Expected error: {e}")
+
+ # Wait for logger to process the failure
+ await asyncio.sleep(5)
+
+ # Verify that our mock upload was called
+ assert upload_called, "S3 upload method was not called"
+ print("✓ S3 upload method was called")
+
+ # Verify that httpx PUT was called
+ s3_v2_logger.async_httpx_client.put.assert_called()
+
+ # Get the call arguments to verify the S3 URL
+ call_args = s3_v2_logger.async_httpx_client.put.call_args
+ assert call_args is not None
+ url = call_args[1]['url'] if 'url' in call_args[1] else call_args[0][0]
+
+ # Verify the URL contains expected S3 endpoint
+ assert "test-bucket.s3.us-west-2.amazonaws.com" in url
+ print(f"✓ S3 PUT request made to: {url}")
+
+ # Verify headers include expected content type
+ headers = call_args[1]['headers']
+ assert headers['Content-Type'] == 'application/json'
+ print("✓ S3 request headers are correct")
+
+ # Verify JSON data was included
+ data = call_args[1]['data']
+ assert data is not None
+ assert '"model": "gpt-4o-mini"' in data
+ print("✓ S3 request data contains expected log payload")
+
+
def list_all_s3_objects(bucket_name):
s3 = boto3.client("s3")