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 errors when callbacks are invoked for file operations
Ephrim Stanley1b6a7ed6c1b2
diff --git a/litellm/_service_logger.py b/litellm/_service_logger.pyindex b67d0d86063..e2759e4fab3 100644--- a/litellm/_service_logger.py+++ b/litellm/_service_logger.py@@ -315,7 +315,7 @@ class ServiceLogging(CustomLogger):await self.async_service_success_hook(service=ServiceTypes.LITELLM,duration=_duration,- call_type=kwargs["call_type"],+ call_type=kwargs.get("call_type", "unknown"))except Exception as e:raise ediff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.pyindex ffc9dbd2372..94886293a08 100644--- a/litellm/proxy/hooks/proxy_track_cost_callback.py+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py@@ -202,7 +202,7 @@ class _ProxyDBLogger(CustomLogger):max_budget=end_user_max_budget,)else:- if sl_object is None and kwargs.get("model") is None:+ if sl_object is None and not kwargs.get("model"):verbose_proxy_logger.warning("Cost tracking - skipping, no standard_logging_object and no model for call_type=%s",kwargs.get("call_type", "unknown"),diff --git a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.pyindex 46da6a89cb2..e8765cf78ca 100644--- a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py+++ b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py@@ -167,3 +167,36 @@ async def test_track_cost_callback_skips_when_no_standard_logging_object():# failed_tracking_alert should NOT be called — this is not an errormock_proxy_logging.failed_tracking_alert.assert_not_called()++[email protected]("model_value", [None, ""])+async def test_track_cost_callback_skips_for_falsy_model_and_no_slo(model_value):+ """+ Same bug as above but model can also be empty string (e.g. health check callbacks).+ The guard should catch all falsy model values when sl_object is missing.+ """+ logger = _ProxyDBLogger()++ kwargs = {+ "call_type": "acompletion",+ "model": model_value,+ "litellm_params": {},+ "stream": False,+ }++ with patch(+ "litellm.proxy.proxy_server.proxy_logging_obj",+ ) as mock_proxy_logging:+ mock_proxy_logging.failed_tracking_alert = AsyncMock()+ mock_proxy_logging.db_spend_update_writer = MagicMock()+ mock_proxy_logging.db_spend_update_writer.update_database = AsyncMock()++ await logger._PROXY_track_cost_callback(+ kwargs=kwargs,+ completion_response=None,+ start_time=datetime.now(),+ end_time=datetime.now(),+ )++ mock_proxy_logging.failed_tracking_alert.assert_not_called()diff --git a/tests/test_litellm/test_service_logger.py b/tests/test_litellm/test_service_logger.pynew file mode 100644index 00000000000..ed44fe9b9f2--- /dev/null+++ b/tests/test_litellm/test_service_logger.py@@ -0,0 +1,97 @@+"""+Tests for litellm/_service_logger.py++Regression test for KeyError: 'call_type' when async_log_success_event+is called without call_type in kwargs (e.g. from batch polling callbacks).+"""++import pytest+from datetime import datetime, timedelta+from unittest.mock import AsyncMock, patch++from litellm._service_logger import ServiceLogging+++async def test_async_log_success_event_should_not_raise_when_call_type_missing():+ """+ When async_log_success_event is called with kwargs that omit 'call_type',+ it should not raise a KeyError. This happens in the batch polling flow+ where check_batch_cost.py creates a Logging object whose model_call_details+ don't include call_type.+ """+ service_logger = ServiceLogging(mock_testing=True)++ start_time = datetime(2026, 2, 13, 22, 35, 0)+ end_time = datetime(2026, 2, 13, 22, 35, 1)+ kwargs_without_call_type = {"model": "gpt-4", "stream": False}++ with patch.object(+ service_logger, "async_service_success_hook", new_callable=AsyncMock+ ) as mock_hook:+ await service_logger.async_log_success_event(+ kwargs=kwargs_without_call_type,+ response_obj=None,+ start_time=start_time,+ end_time=end_time,+ )++ mock_hook.assert_called_once()+ call_kwargs = mock_hook.call_args+ assert call_kwargs.kwargs["call_type"] == "unknown"+++async def test_async_log_success_event_should_pass_call_type_when_present():+ """+ When call_type IS present in kwargs, it should be forwarded correctly.+ """+ service_logger = ServiceLogging(mock_testing=True)++ start_time = datetime(2026, 2, 13, 22, 35, 0)+ end_time = datetime(2026, 2, 13, 22, 35, 1)+ kwargs_with_call_type = {+ "model": "gpt-4",+ "stream": False,+ "call_type": "aretrieve_batch",+ }++ with patch.object(+ service_logger, "async_service_success_hook", new_callable=AsyncMock+ ) as mock_hook:+ await service_logger.async_log_success_event(+ kwargs=kwargs_with_call_type,+ response_obj=None,+ start_time=start_time,+ end_time=end_time,+ )++ mock_hook.assert_called_once()+ call_kwargs = mock_hook.call_args+ assert call_kwargs.kwargs["call_type"] == "aretrieve_batch"+++async def test_async_log_success_event_should_handle_float_duration():+ """+ When start_time and end_time produce a float duration (not timedelta),+ it should still work correctly.+ """+ service_logger = ServiceLogging(mock_testing=True)++ start_time = 1000.0+ end_time = 1001.5++ with patch.object(+ service_logger, "async_service_success_hook", new_callable=AsyncMock+ ) as mock_hook:+ await service_logger.async_log_success_event(+ kwargs={"call_type": "completion"},+ response_obj=None,+ start_time=start_time,+ end_time=end_time,+ )++ mock_hook.assert_called_once()+ call_kwargs = mock_hook.call_args+ assert call_kwargs.kwargs["duration"] == 1.5