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] turn_off_message_logging Does Not Redact Request Messages in proxy_server_request Field When Stored to Database (#18897)
Ishaan Jaffab50fea6636c
diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.pyindex 1c457d7bf4c..5d348d35cb2 100644--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py@@ -1,3 +1,4 @@+import copyimport hashlibimport jsonimport secrets@@ -433,9 +434,11 @@ def get_logging_payload( # noqa: PLR0915messages=_get_messages_for_spend_logs_payload(standard_logging_payload=standard_logging_payload, metadata=metadata),- response=_get_response_for_spend_logs_payload(standard_logging_payload),+ response=_get_response_for_spend_logs_payload(+ payload=standard_logging_payload, kwargs=kwargs+ ),proxy_server_request=_get_proxy_server_request_for_spend_logs_payload(- metadata=metadata, litellm_params=litellm_params+ metadata=metadata, litellm_params=litellm_params, kwargs=kwargs),session_id=_get_session_id_for_spend_log(kwargs=kwargs,@@ -642,9 +645,12 @@ def _sanitize_request_body_for_spend_logs_payload(def _get_proxy_server_request_for_spend_logs_payload(metadata: dict,litellm_params: dict,+ kwargs: Optional[dict] = None,) -> str:"""Only store if _should_store_prompts_and_responses_in_spend_logs() is True++ If turn_off_message_logging is enabled, redact messages in the request body."""if _should_store_prompts_and_responses_in_spend_logs():_proxy_server_request = cast(@@ -652,6 +658,27 @@ def _get_proxy_server_request_for_spend_logs_payload()if _proxy_server_request is not None:_request_body = _proxy_server_request.get("body", {}) or {}++ # Apply message redaction if turn_off_message_logging is enabled+ if kwargs is not None:+ from litellm.litellm_core_utils.redact_messages import (+ perform_redaction,+ should_redact_message_logging,+ )++ # Build model_call_details dict to check redaction settings+ model_call_details = {+ "litellm_params": litellm_params,+ "standard_callback_dynamic_params": kwargs.get(+ "standard_callback_dynamic_params"+ ),+ }++ # If redaction is enabled, deep copy request body before redacting+ if should_redact_message_logging(model_call_details=model_call_details):+ _request_body = copy.deepcopy(_request_body)+ perform_redaction(model_call_details=_request_body, result=None)+_request_body = _sanitize_request_body_for_spend_logs_payload(_request_body)_request_body_json_str = json.dumps(_request_body, default=str)return _request_body_json_str@@ -685,6 +712,7 @@ def _get_vector_store_request_for_spend_logs_payload(def _get_response_for_spend_logs_payload(payload: Optional[StandardLoggingPayload],+ kwargs: Optional[dict] = None,) -> str:if payload is None:return "{}"@@ -692,6 +720,26 @@ def _get_response_for_spend_logs_payload(response_obj: Any = payload.get("response")if response_obj is None:return "{}"++ # Apply message redaction if turn_off_message_logging is enabled+ if kwargs is not None:+ from litellm.litellm_core_utils.redact_messages import (+ perform_redaction,+ should_redact_message_logging,+ )++ litellm_params = kwargs.get("litellm_params", {})+ model_call_details = {+ "litellm_params": litellm_params,+ "standard_callback_dynamic_params": kwargs.get(+ "standard_callback_dynamic_params"+ ),+ }++ # If redaction is enabled, deep copy response before redacting+ if should_redact_message_logging(model_call_details=model_call_details):+ response_obj = copy.deepcopy(response_obj)+ response_obj = perform_redaction(model_call_details={}, result=response_obj)sanitized_wrapper = _sanitize_request_body_for_spend_logs_payload({"response": response_obj}diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.pyindex 69b7e504184..dd4cbfa2e7f 100644--- a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py@@ -19,6 +19,7 @@ import litellmfrom litellm.constants import LITELLM_TRUNCATED_PAYLOAD_FIELD, REDACTED_BY_LITELM_STRINGfrom litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom litellm.proxy.spend_tracking.spend_tracking_utils import (+ _get_proxy_server_request_for_spend_logs_payload,_get_response_for_spend_logs_payload,_get_vector_store_request_for_spend_logs_payload,_sanitize_request_body_for_spend_logs_payload,@@ -850,3 +851,63 @@ def test_get_logging_payload_handles_missing_overhead_gracefully():metadata.get("litellm_overhead_time_ms") is None), "litellm_overhead_time_ms should be None when overhead is not provided"++@patch(+ "litellm.proxy.spend_tracking.spend_tracking_utils._should_store_prompts_and_responses_in_spend_logs"+)+def test_spend_logs_redacts_request_and_response_when_turn_off_message_logging_enabled(+ mock_should_store,+):+ """+ Test that both request body and response are redacted when turn_off_message_logging is enabled.+ """+ mock_should_store.return_value = True++ # Test request redaction+ litellm_params = {+ "proxy_server_request": {+ "body": {+ "messages": [{"role": "user", "content": "secret message"}],+ "model": "gpt-4",+ }+ }+ }+ metadata = {}+ kwargs = {+ "litellm_params": litellm_params,+ "standard_callback_dynamic_params": {+ "turn_off_message_logging": True,+ },+ }++ request_result = _get_proxy_server_request_for_spend_logs_payload(+ metadata=metadata, litellm_params=litellm_params, kwargs=kwargs+ )++ parsed_request = json.loads(request_result)+ assert parsed_request["messages"] == [{"role": "user", "content": "redacted-by-litellm"}]+ assert parsed_request["model"] == "gpt-4"++ # Test response redaction - use dict response to verify redaction+ response_dict = {+ "id": "test-id",+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": "secret response"},+ }+ ],+ "model": "gpt-4",+ }+ payload = cast(+ StandardLoggingPayload,+ {"response": response_dict},+ )++ response_result = _get_response_for_spend_logs_payload(payload=payload, kwargs=kwargs)++ # When redaction is enabled and response is a dict (not ModelResponse),+ # perform_redaction returns {"text": "redacted-by-litellm"}+ parsed_response = json.loads(response_result)+ assert parsed_response == {"text": "redacted-by-litellm"}+