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): OpenAI Moderation post-call guardrail response not captured for logging
michelligabrieleae454fd7005a
diff --git a/litellm/llms/a2a/chat/guardrail_translation/handler.py b/litellm/llms/a2a/chat/guardrail_translation/handler.pyindex fbd1da749c2..91e7e9d5550 100644--- a/litellm/llms/a2a/chat/guardrail_translation/handler.py+++ b/litellm/llms/a2a/chat/guardrail_translation/handler.py@@ -111,6 +111,7 @@ class A2AGuardrailHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,user_api_key_dict: Optional["UserAPIKeyAuth"] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process A2A output response by applying guardrails to text content.@@ -166,13 +167,21 @@ class A2AGuardrailHandler(BaseTranslation):return response# Step 2: Apply guardrail to all texts in batch- # Create a request_data dict with response info and user API key metadata- request_data: dict = {"response": response_dict}+ # Use the real request_data if provided (proxy path), otherwise+ # create a standalone dict (SDK / direct-call path).+ if request_data is None:+ request_data = {"response": response_dict}+ else:+ if "response" not in request_data:+ request_data["response"] = response_dict# Add user API key metadata with prefixed keys- user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict)- if user_metadata:- request_data["litellm_metadata"] = user_metadata+ if "litellm_metadata" not in request_data:+ user_metadata = self.transform_user_api_key_dict_to_metadata(+ user_api_key_dict+ )+ if user_metadata:+ request_data["litellm_metadata"] = user_metadatainputs = GenericGuardrailAPIInputs(texts=texts_to_check)@@ -213,6 +222,7 @@ class A2AGuardrailHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,user_api_key_dict: Optional["UserAPIKeyAuth"] = None,+ request_data: Optional[dict] = None,) -> List[Any]:"""Process A2A streaming output by applying guardrails to accumulated text.@@ -258,10 +268,18 @@ class A2AGuardrailHandler(BaseTranslation):if not combined_text:return responses_so_far- request_data: dict = {"responses_so_far": responses_so_far}- user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict)- if user_metadata:- request_data["litellm_metadata"] = user_metadata+ if request_data is None:+ request_data = {"responses_so_far": responses_so_far}+ else:+ if "responses_so_far" not in request_data:+ request_data["responses_so_far"] = responses_so_far++ if "litellm_metadata" not in request_data:+ user_metadata = self.transform_user_api_key_dict_to_metadata(+ user_api_key_dict+ )+ if user_metadata:+ request_data["litellm_metadata"] = user_metadatainputs = GenericGuardrailAPIInputs(texts=[combined_text])guardrailed_inputs = await guardrail_to_apply.apply_guardrail(diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.pyindex 5372757cbb6..b6139a2f84d 100644--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py@@ -252,6 +252,7 @@ class AnthropicMessagesHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output response by applying guardrails to text content and tool calls.@@ -323,15 +324,21 @@ class AnthropicMessagesHandler(BaseTranslation):# Step 2: Apply guardrail to all texts in batchif texts_to_check or tool_calls_to_check:- # Create a request_data dict with response info and user API key metadata- request_data: dict = {"response": response}+ # Use the real request_data if provided (proxy path), otherwise+ # create a standalone dict (SDK / direct-call path).+ if request_data is None:+ request_data = {"response": response}+ else:+ if "response" not in request_data:+ request_data["response"] = response# Add user API key metadata with prefixed keys- user_metadata = self.transform_user_api_key_dict_to_metadata(- user_api_key_dict- )- if user_metadata:- request_data["litellm_metadata"] = user_metadata+ if "litellm_metadata" not in request_data:+ user_metadata = self.transform_user_api_key_dict_to_metadata(+ user_api_key_dict+ )+ if user_metadata:+ request_data["litellm_metadata"] = user_metadatainputs = GenericGuardrailAPIInputs(texts=texts_to_check)if images_to_check:@@ -375,6 +382,7 @@ class AnthropicMessagesHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> List[Any]:"""Process output streaming response by applying guardrails to text content.@@ -413,7 +421,7 @@ class AnthropicMessagesHandler(BaseTranslation):_guardrailed_inputs = await guardrail_to_apply.apply_guardrail( # allow rejecting the response, if invalidinputs=guardrail_inputs,- request_data={},+ request_data=request_data if request_data is not None else {},input_type="response",logging_obj=litellm_logging_obj,)@@ -426,7 +434,7 @@ class AnthropicMessagesHandler(BaseTranslation):string_so_far = self.get_streaming_string_so_far(responses_so_far)_guardrailed_inputs = await guardrail_to_apply.apply_guardrail( # allow rejecting the response, if invalidinputs={"texts": [string_so_far]},- request_data={},+ request_data=request_data if request_data is not None else {},input_type="response",logging_obj=litellm_logging_obj,)diff --git a/litellm/llms/base_llm/guardrail_translation/base_translation.py b/litellm/llms/base_llm/guardrail_translation/base_translation.pyindex a7982cb606e..e1da0dfa29e 100644--- a/litellm/llms/base_llm/guardrail_translation/base_translation.py+++ b/litellm/llms/base_llm/guardrail_translation/base_translation.py@@ -73,6 +73,7 @@ class BaseTranslation(ABC):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,user_api_key_dict: Optional["UserAPIKeyAuth"] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output response with guardrails.@@ -91,6 +92,7 @@ class BaseTranslation(ABC):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,user_api_key_dict: Optional["UserAPIKeyAuth"] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output streaming response with guardrails.diff --git a/litellm/llms/cohere/rerank/guardrail_translation/handler.py b/litellm/llms/cohere/rerank/guardrail_translation/handler.pyindex b8133c59f7d..e9a5823d2b8 100644--- a/litellm/llms/cohere/rerank/guardrail_translation/handler.py+++ b/litellm/llms/cohere/rerank/guardrail_translation/handler.py@@ -83,6 +83,7 @@ class CohereRerankHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output response - not applicable for rerank.diff --git a/litellm/llms/mistral/ocr/guardrail_translation/handler.py b/litellm/llms/mistral/ocr/guardrail_translation/handler.pyindex 697bd2daa3d..795ce1d7cae 100644--- a/litellm/llms/mistral/ocr/guardrail_translation/handler.py+++ b/litellm/llms/mistral/ocr/guardrail_translation/handler.py@@ -91,6 +91,7 @@ class OCRHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process OCR output by applying guardrails to extracted page text.@@ -127,14 +128,22 @@ class OCRHandler(BaseTranslation):if model:inputs["model"] = model+ # Use the real request_data if provided (proxy path), otherwise+ # create a standalone dict (SDK / direct-call path).+ if request_data is None:+ request_data = {}+# Add user metadata if available- if user_api_key_dict is not None:- metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict)- inputs.update(metadata) # type: ignore+ if "litellm_metadata" not in request_data and user_api_key_dict is not None:+ user_metadata = self.transform_user_api_key_dict_to_metadata(+ user_api_key_dict+ )+ if user_metadata:+ request_data["litellm_metadata"] = user_metadataguardrailed_inputs = await guardrail_to_apply.apply_guardrail(inputs=inputs,- request_data={},+ request_data=request_data,input_type="response",logging_obj=litellm_logging_obj,)diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.pyindex bab4c3b5eb7..f854cdb13d0 100644--- a/litellm/llms/openai/chat/guardrail_translation/handler.py+++ b/litellm/llms/openai/chat/guardrail_translation/handler.py@@ -260,6 +260,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output response by applying guardrails to text content.@@ -308,15 +309,21 @@ class OpenAIChatCompletionsHandler(BaseTranslation):# Step 2: Apply guardrail to all texts and tool calls in batchif texts_to_check or tool_calls_to_check:- # Create a request_data dict with response info and user API key metadata- request_data: dict = {"response": response}+ # Use the real request_data if provided (proxy path), otherwise+ # create a standalone dict (SDK / direct-call path).+ if request_data is None:+ request_data = {"response": response}+ else:+ if "response" not in request_data:+ request_data["response"] = response# Add user API key metadata with prefixed keys- user_metadata = self.transform_user_api_key_dict_to_metadata(- user_api_key_dict- )- if user_metadata:- request_data["litellm_metadata"] = user_metadata+ if "litellm_metadata" not in request_data:+ user_metadata = self.transform_user_api_key_dict_to_metadata(+ user_api_key_dict+ )+ if user_metadata:+ request_data["litellm_metadata"] = user_metadatainputs = GenericGuardrailAPIInputs(texts=texts_to_check)if images_to_check:@@ -364,6 +371,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> List["ModelResponseStream"]:"""Process output streaming responses by applying guardrails to text content.@@ -402,6 +410,7 @@ class OpenAIChatCompletionsHandler(BaseTranslation):guardrail_to_apply=guardrail_to_apply,litellm_logging_obj=litellm_logging_obj,user_api_key_dict=user_api_key_dict,+ request_data=request_data,)return responses_so_far@@ -436,15 +445,21 @@ class OpenAIChatCompletionsHandler(BaseTranslation):# Step 3: Apply guardrail to all combined texts in batchif texts_to_check:- # Create a request_data dict with response info and user API key metadata- request_data: dict = {"responses": responses_so_far}+ # Use the real request_data if provided (proxy path), otherwise+ # create a standalone dict (SDK / direct-call path).+ if request_data is None:+ request_data = {"responses": responses_so_far}+ else:+ if "responses" not in request_data:+ request_data["responses"] = responses_so_far# Add user API key metadata with prefixed keys- user_metadata = self.transform_user_api_key_dict_to_metadata(- user_api_key_dict- )- if user_metadata:- request_data["litellm_metadata"] = user_metadata+ if "litellm_metadata" not in request_data:+ user_metadata = self.transform_user_api_key_dict_to_metadata(+ user_api_key_dict+ )+ if user_metadata:+ request_data["litellm_metadata"] = user_metadatainputs = GenericGuardrailAPIInputs(texts=texts_to_check)if images_to_check:diff --git a/litellm/llms/openai/completion/guardrail_translation/handler.py b/litellm/llms/openai/completion/guardrail_translation/handler.pyindex 1f8c6159da0..593ab0ed2e5 100644--- a/litellm/llms/openai/completion/guardrail_translation/handler.py+++ b/litellm/llms/openai/completion/guardrail_translation/handler.py@@ -125,6 +125,7 @@ class OpenAITextCompletionHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output response by applying guardrails to completion text.@@ -155,15 +156,21 @@ class OpenAITextCompletionHandler(BaseTranslation):# Apply guardrails in batchif texts_to_check:- # Create a request_data dict with response info and user API key metadata- request_data: dict = {"response": response}+ # Use the real request_data if provided (proxy path), otherwise+ # create a standalone dict (SDK / direct-call path).+ if request_data is None:+ request_data = {"response": response}+ else:+ if "response" not in request_data:+ request_data["response"] = response# Add user API key metadata with prefixed keys- user_metadata = self.transform_user_api_key_dict_to_metadata(- user_api_key_dict- )- if user_metadata:- request_data["litellm_metadata"] = user_metadata+ if "litellm_metadata" not in request_data:+ user_metadata = self.transform_user_api_key_dict_to_metadata(+ user_api_key_dict+ )+ if user_metadata:+ request_data["litellm_metadata"] = user_metadatainputs = GenericGuardrailAPIInputs(texts=texts_to_check)# Include model information from the response if availablediff --git a/litellm/llms/openai/embeddings/guardrail_translation/handler.py b/litellm/llms/openai/embeddings/guardrail_translation/handler.pyindex 7458020e109..ff5021b8ce0 100644--- a/litellm/llms/openai/embeddings/guardrail_translation/handler.py+++ b/litellm/llms/openai/embeddings/guardrail_translation/handler.py@@ -155,6 +155,7 @@ class OpenAIEmbeddingsHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output response - embeddings responses contain vectors, not text.diff --git a/litellm/llms/openai/image_generation/guardrail_translation/handler.py b/litellm/llms/openai/image_generation/guardrail_translation/handler.pyindex e6340ba4705..76610088d0c 100644--- a/litellm/llms/openai/image_generation/guardrail_translation/handler.py+++ b/litellm/llms/openai/image_generation/guardrail_translation/handler.py@@ -87,6 +87,7 @@ class OpenAIImageGenerationHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output response - typically not needed for image generation.diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.pyindex 466e2e76f18..ede5377c3fd 100644--- a/litellm/llms/openai/responses/guardrail_translation/handler.py+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py@@ -347,6 +347,7 @@ class OpenAIResponsesHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output response by applying guardrails to text content and tool calls.@@ -402,15 +403,21 @@ class OpenAIResponsesHandler(BaseTranslation):# Step 2: Apply guardrail to all texts in batchif texts_to_check or tool_calls_to_check:- # Create a request_data dict with response info and user API key metadata- request_data: dict = {"response": response}+ # Use the real request_data if provided (proxy path), otherwise+ # create a standalone dict (SDK / direct-call path).+ if request_data is None:+ request_data = {"response": response}+ else:+ if "response" not in request_data:+ request_data["response"] = response# Add user API key metadata with prefixed keys- user_metadata = self.transform_user_api_key_dict_to_metadata(- user_api_key_dict- )- if user_metadata:- request_data["litellm_metadata"] = user_metadata+ if "litellm_metadata" not in request_data:+ user_metadata = self.transform_user_api_key_dict_to_metadata(+ user_api_key_dict+ )+ if user_metadata:+ request_data["litellm_metadata"] = user_metadatainputs = GenericGuardrailAPIInputs(texts=texts_to_check)if images_to_check:@@ -454,6 +461,7 @@ class OpenAIResponsesHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> List[Any]:"""Process output streaming response by applying guardrails to text content.@@ -481,7 +489,7 @@ class OpenAIResponsesHandler(BaseTranslation):inputs["model"] = model_response_stream.model_guardrailed_inputs = await guardrail_to_apply.apply_guardrail(inputs=inputs,- request_data={},+ request_data=request_data if request_data is not None else {},input_type="response",logging_obj=litellm_logging_obj,)@@ -512,7 +520,7 @@ class OpenAIResponsesHandler(BaseTranslation):if tool_calls or text:_guardrailed_inputs = await guardrail_to_apply.apply_guardrail(inputs=guardrail_inputs,- request_data={},+ request_data=request_data if request_data is not None else {},input_type="response",logging_obj=litellm_logging_obj,)diff --git a/litellm/llms/openai/speech/guardrail_translation/handler.py b/litellm/llms/openai/speech/guardrail_translation/handler.pyindex e6796fbac2a..f0c3149d0ae 100644--- a/litellm/llms/openai/speech/guardrail_translation/handler.py+++ b/litellm/llms/openai/speech/guardrail_translation/handler.py@@ -85,6 +85,7 @@ class OpenAITextToSpeechHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output - not applicable for text-to-speech.diff --git a/litellm/llms/openai/transcriptions/guardrail_translation/handler.py b/litellm/llms/openai/transcriptions/guardrail_translation/handler.pyindex 3d76a21c389..92cf4398f05 100644--- a/litellm/llms/openai/transcriptions/guardrail_translation/handler.py+++ b/litellm/llms/openai/transcriptions/guardrail_translation/handler.py@@ -58,6 +58,7 @@ class OpenAIAudioTranscriptionHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output transcription by applying guardrails to transcribed text.@@ -79,15 +80,21 @@ class OpenAIAudioTranscriptionHandler(BaseTranslation):if isinstance(response.text, str):original_text = response.text- # Create a request_data dict with response info and user API key metadata- request_data: dict = {"response": response}+ # Use the real request_data if provided (proxy path), otherwise+ # create a standalone dict (SDK / direct-call path).+ if request_data is None:+ request_data = {"response": response}+ else:+ if "response" not in request_data:+ request_data["response"] = response# Add user API key metadata with prefixed keys- user_metadata = self.transform_user_api_key_dict_to_metadata(- user_api_key_dict- )- if user_metadata:- request_data["litellm_metadata"] = user_metadata+ if "litellm_metadata" not in request_data:+ user_metadata = self.transform_user_api_key_dict_to_metadata(+ user_api_key_dict+ )+ if user_metadata:+ request_data["litellm_metadata"] = user_metadatainputs = GenericGuardrailAPIInputs(texts=[original_text])# Include model information from the response if availablediff --git a/litellm/llms/pass_through/guardrail_translation/handler.py b/litellm/llms/pass_through/guardrail_translation/handler.pyindex 40433d53413..a8cc42d7c54 100644--- a/litellm/llms/pass_through/guardrail_translation/handler.py+++ b/litellm/llms/pass_through/guardrail_translation/handler.py@@ -139,6 +139,7 @@ class PassThroughEndpointHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional["LiteLLMLoggingObj"] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:"""Process output response by applying guardrails to targeted fields.@@ -171,17 +172,27 @@ class PassThroughEndpointHandler(BaseTranslation):if not text_to_check:return response- # Create a request_data dict with response info and user API key metadata- request_data: dict = (- {"response": response}- if not isinstance(response, dict)- else response.copy()- )+ # Use the real request_data if provided (proxy path), otherwise+ # create a standalone dict (SDK / direct-call path).+ if request_data is None:+ request_data = (+ {"response": response}+ if not isinstance(response, dict)+ else response.copy()+ )+ else:+ if "response" not in request_data:+ request_data["response"] = (+ response if not isinstance(response, dict) else response.copy()+ )# Add user API key metadata with prefixed keys- user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict)- if user_metadata:- request_data["litellm_metadata"] = user_metadata+ if "litellm_metadata" not in request_data:+ user_metadata = self.transform_user_api_key_dict_to_metadata(+ user_api_key_dict+ )+ if user_metadata:+ request_data["litellm_metadata"] = user_metadata# Apply guardrail (pass-through doesn't modify the text, just checks it)inputs = GenericGuardrailAPIInputs(texts=[text_to_check])diff --git a/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py b/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.pyindex 14bbb82808d..6997f5241de 100644--- a/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py+++ b/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py@@ -92,6 +92,7 @@ class MCPGuardrailTranslationHandler(BaseTranslation):guardrail_to_apply: "CustomGuardrail",litellm_logging_obj: Optional[Any] = None,user_api_key_dict: Optional[Any] = None,+ request_data: Optional[dict] = None,) -> Any:verbose_proxy_logger.debug("MCP Guardrail: Output processing not implemented for MCP tools",diff --git a/litellm/proxy/guardrails/guardrail_hooks/openai/moderations.py b/litellm/proxy/guardrails/guardrail_hooks/openai/moderations.pyindex 4bd94345727..6da8f9acbf4 100644--- a/litellm/proxy/guardrails/guardrail_hooks/openai/moderations.py+++ b/litellm/proxy/guardrails/guardrail_hooks/openai/moderations.py@@ -5,9 +5,11 @@ OpenAI Moderation Guardrail Integration for LiteLLMfrom typing import (TYPE_CHECKING,+ Dict,Literal,Optional,Type,+ Union,)from fastapi import HTTPException@@ -22,7 +24,8 @@ from litellm.llms.custom_httpx.http_handler import (get_async_httpx_client,httpxSpecialProvider,)-from litellm.types.utils import GenericGuardrailAPIInputs+from litellm.types.guardrails import GuardrailEventHooks+from litellm.types.utils import GenericGuardrailAPIInputs, GuardrailStatusfrom .base import OpenAIGuardrailBase@@ -223,12 +226,94 @@ class OpenAIModerationGuardrail(OpenAIGuardrailBase, CustomGuardrail):# Make moderation requestmoderation_response = await self.async_make_request(input_text=text_to_moderate)+ # Stash full moderation response in request_data for logging+ # (Model Armor pattern — per-request dict avoids race conditions)+ if isinstance(request_data, dict):+ metadata = request_data.get("metadata") or {}+ request_data["metadata"] = metadata+ metadata["_openai_moderation_response"] = moderation_response.model_dump()+# Check if content is flagged and raise exception if neededself._check_moderation_result(moderation_response)# Moderation doesn't modify content, just blocks - return inputs unchangedreturn inputs+ def _process_response(+ self,+ response: Optional[Dict],+ request_data: dict,+ start_time: Optional[float] = None,+ end_time: Optional[float] = None,+ duration: Optional[float] = None,+ event_type: Optional[GuardrailEventHooks] = None,+ original_inputs: Optional[Dict] = None,+ ):+ """+ Override to log the full OpenAI Moderation API response instead of+ the decorator's simplified "allow"/"mask" string.++ Follows the Model Armor pattern (model_armor.py:325-360).+ """+ metadata = (+ (request_data.get("metadata") or {}) if isinstance(request_data, dict) else {}+ )++ # .pop() cleans up the internal key so it doesn't leak to downstream+ # loggers. Falls back to "allow" when no moderation call was made+ # (e.g. no text to moderate — early return in apply_guardrail).+ guardrail_response = metadata.pop("_openai_moderation_response", "allow")++ self.add_standard_logging_guardrail_information_to_request_data(+ guardrail_json_response=guardrail_response,+ request_data=request_data,+ guardrail_status="success",+ duration=duration,+ start_time=start_time,+ end_time=end_time,+ event_type=event_type,+ )+ return response++ def _process_error(+ self,+ e: Exception,+ request_data: dict,+ start_time: Optional[float] = None,+ end_time: Optional[float] = None,+ duration: Optional[float] = None,+ event_type: Optional[GuardrailEventHooks] = None,+ ):+ """+ Override to log the full OpenAI Moderation API response on error+ instead of the stringified exception.+ """+ guardrail_status: GuardrailStatus = (+ "guardrail_intervened"+ if self._is_guardrail_intervention(e)+ else "guardrail_failed_to_respond"+ )++ metadata = (+ (request_data.get("metadata") or {}) if isinstance(request_data, dict) else {}+ )++ # Use the stashed moderation response if available, fall back to exception+ guardrail_response: Union[dict, Exception, str] = metadata.pop(+ "_openai_moderation_response", e+ )++ self.add_standard_logging_guardrail_information_to_request_data(+ guardrail_json_response=guardrail_response,+ request_data=request_data,+ guardrail_status=guardrail_status,+ duration=duration,+ start_time=start_time,+ end_time=end_time,+ event_type=event_type,+ )+ raise e+@staticmethoddef get_config_model() -> Optional[Type["GuardrailConfigModel"]]:"""diff --git a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.pyindex 84bbf6d20e1..80b6f987f66 100644--- a/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py+++ b/litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py@@ -247,6 +247,7 @@ class UnifiedLLMGuardrails(CustomLogger):guardrail_to_apply=guardrail_to_apply,litellm_logging_obj=data.get("litellm_logging_obj"),user_api_key_dict=user_api_key_dict,+ request_data=data,)# Add guardrail to applied guardrails headeradd_guardrail_to_applied_guardrails_header(@@ -397,6 +398,7 @@ class UnifiedLLMGuardrails(CustomLogger):guardrail_to_apply=guardrail_to_apply,litellm_logging_obj=request_data.get("litellm_logging_obj"),user_api_key_dict=user_api_key_dict,+ request_data=request_data,)except HTTPException as e:# Response already started (we already yielded chunks); cannot send 400.diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/openai/test_moderations.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/openai/test_moderations.pyindex 3a17bbd0025..bb6d7865d48 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/openai/test_moderations.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/openai/test_moderations.py@@ -488,3 +488,245 @@ async def test_openai_moderation_guardrail_streaming_harmful_content():assert exc_info.value.status_code == 400assert "Violated OpenAI moderation policy" in str(exc_info.value.detail)+++async def test_openai_moderation_guardrail_logs_full_response_safe_content():+ """Test that safe content logs the full moderation response (categories, scores)+ in StandardLoggingGuardrailInformation, not just 'allow'."""+ from litellm.types.utils import GenericGuardrailAPIInputs++ with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):+ guardrail = OpenAIModerationGuardrail(+ guardrail_name="test-openai-moderation",+ )++ mock_response = OpenAIModerationResponse(+ id="modr-123",+ model="omni-moderation-latest",+ results=[+ OpenAIModerationResult(+ flagged=False,+ categories={+ "sexual": False,+ "hate": False,+ "harassment": False,+ "self-harm": False,+ "violence": False,+ },+ category_scores={+ "sexual": 0.001,+ "hate": 0.002,+ "harassment": 0.001,+ "self-harm": 0.001,+ "violence": 0.003,+ },+ category_applied_input_types={+ "sexual": [],+ "hate": [],+ "harassment": [],+ "self-harm": [],+ "violence": [],+ },+ )+ ],+ )++ with patch.object(guardrail, "async_make_request", return_value=mock_response):+ inputs = GenericGuardrailAPIInputs(+ structured_messages=[+ {"role": "user", "content": "Hello, how are you?"}+ ]+ )+ request_data = {"metadata": {}}++ await guardrail.apply_guardrail(+ inputs=inputs,+ request_data=request_data,+ input_type="request",+ )++ guardrail_info_list = request_data["metadata"][+ "standard_logging_guardrail_information"+ ]+ assert len(guardrail_info_list) == 1++ info = guardrail_info_list[0]+ assert info["guardrail_name"] == "test-openai-moderation"+ assert info["guardrail_status"] == "success"++ # Full moderation response, NOT "allow"+ guardrail_resp = info["guardrail_response"]+ assert isinstance(guardrail_resp, dict)+ assert guardrail_resp["results"][0]["flagged"] is False+ assert "category_scores" in guardrail_resp["results"][0]++ # Internal key cleaned up (.pop())+ assert "_openai_moderation_response" not in request_data["metadata"]+++async def test_openai_moderation_guardrail_logs_full_response_harmful_content():+ """Test that harmful content logs guardrail_intervened status with the full+ moderation response, not just the exception string."""+ from litellm.types.utils import GenericGuardrailAPIInputs++ with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):+ guardrail = OpenAIModerationGuardrail(+ guardrail_name="test-openai-moderation",+ )++ mock_response = OpenAIModerationResponse(+ id="modr-456",+ model="omni-moderation-latest",+ results=[+ OpenAIModerationResult(+ flagged=True,+ categories={+ "sexual": False,+ "hate": True,+ "harassment": False,+ "self-harm": False,+ "violence": False,+ },+ category_scores={+ "sexual": 0.001,+ "hate": 0.95,+ "harassment": 0.001,+ "self-harm": 0.001,+ "violence": 0.001,+ },+ category_applied_input_types={+ "sexual": [],+ "hate": ["text"],+ "harassment": [],+ "self-harm": [],+ "violence": [],+ },+ )+ ],+ )++ with patch.object(guardrail, "async_make_request", return_value=mock_response):+ inputs = GenericGuardrailAPIInputs(+ structured_messages=[+ {"role": "user", "content": "Hateful content"}+ ]+ )+ request_data = {"metadata": {}}++ from fastapi import HTTPException++ with pytest.raises(HTTPException):+ await guardrail.apply_guardrail(+ inputs=inputs,+ request_data=request_data,+ input_type="request",+ )++ guardrail_info_list = request_data["metadata"][+ "standard_logging_guardrail_information"+ ]+ info = guardrail_info_list[0]+ assert info["guardrail_status"] == "guardrail_intervened"++ # Full moderation response, NOT stringified exception+ guardrail_resp = info["guardrail_response"]+ assert isinstance(guardrail_resp, dict)+ assert guardrail_resp["results"][0]["flagged"] is True+ assert guardrail_resp["results"][0]["category_scores"]["hate"] == 0.95++ # Internal key cleaned up by _process_error (.pop())+ assert "_openai_moderation_response" not in request_data["metadata"]+++async def test_openai_moderation_post_call_request_data_passthrough():+ """Test that post-call guardrail info flows through to the real request_data+ via the unified guardrail dispatcher (Bug 1 fix)."""+ from unittest.mock import AsyncMock++ from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (+ UnifiedLLMGuardrails,+ )+ from litellm.types.utils import ModelResponse++ import litellm++ with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}):+ guardrail = OpenAIModerationGuardrail(+ guardrail_name="test-openai-moderation",+ event_hook="post_call",+ )+ unified_guardrail = UnifiedLLMGuardrails()++ mock_mod_response = OpenAIModerationResponse(+ id="modr-789",+ model="omni-moderation-latest",+ results=[+ OpenAIModerationResult(+ flagged=False,+ categories={+ "sexual": False,+ "hate": False,+ "harassment": False,+ "self-harm": False,+ "violence": False,+ },+ category_scores={+ "sexual": 0.001,+ "hate": 0.002,+ "harassment": 0.001,+ "self-harm": 0.001,+ "violence": 0.001,+ },+ category_applied_input_types={+ "sexual": [],+ "hate": [],+ "harassment": [],+ "self-harm": [],+ "violence": [],+ },+ )+ ],+ )++ llm_response = ModelResponse(+ id="chatcmpl-test",+ model="gpt-4",+ choices=[+ litellm.Choices(+ index=0,+ message=litellm.Message(+ role="assistant", content="Hello world"+ ),+ finish_reason="stop",+ )+ ],+ )++ request_data = {+ "messages": [{"role": "user", "content": "Hello"}],+ "guardrail_to_apply": guardrail,+ "metadata": {"guardrails": ["test-openai-moderation"]},+ }++ mock_make_request = AsyncMock(return_value=mock_mod_response)+ with patch.object(guardrail, "async_make_request", mock_make_request):+ await unified_guardrail.async_post_call_success_hook(+ data=request_data,+ user_api_key_dict=UserAPIKeyAuth(+ api_key="test", request_route="/chat/completions"+ ),+ response=llm_response,+ )++ mock_make_request.assert_called_once()++ # Guardrail info in the REAL request_data (not a throwaway)+ guardrail_info_list = request_data["metadata"].get(+ "standard_logging_guardrail_information"+ )+ assert guardrail_info_list is not None+ assert isinstance(guardrail_info_list[0]["guardrail_response"], dict)+ assert "results" in guardrail_info_list[0]["guardrail_response"]