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]

fix(bedrock guardrail): dedupe post-call log entry when only post_call is configured (#26474)

Shivam Rawat5416a7c86e14
diff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
index 8bfe5027b77..e5df26b7c2c 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
@@ -1098,58 +1098,21 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):
#########################################################
########## 1. Make Bedrock API requests ##########
#########################################################
- # Import asyncio for parallel execution
- import asyncio
-
- # Determine if INPUT validation is needed in post_call
- # Skip INPUT validation if pre_call or during_call is already enabled
- # (to avoid redundant validation - those hooks would have already validated INPUT)
- should_validate_input = not (
- self._event_hook_is_event_type(GuardrailEventHooks.pre_call)
- or self._event_hook_is_event_type(GuardrailEventHooks.during_call)
- )
-
+ # post_call is the response-validation hook by definition — only scan
+ # OUTPUT. Input scanning belongs to pre_call / during_call hooks, which
+ # users should configure if they want input validation. Running an
+ # extra INPUT scan here produced a duplicate post-call entry in the
+ # trace and made no semantic sense for a "post-call" event.
output_content_bedrock: Optional[Union[BedrockGuardrailResponse, str]] = None
-
- if should_validate_input:
- # Prepare input messages (with optional filtering for latest role message)
- input_filter = self._prepare_guardrail_messages_for_role(
- messages=new_messages
- )
- input_messages = input_filter.payload_messages or new_messages
-
- # Create tasks for parallel execution of both INPUT and OUTPUT validation
- input_task = self.make_bedrock_api_request(
- source="INPUT",
- messages=input_messages,
- request_data=data,
- logging_event_type=GuardrailEventHooks.post_call,
- )
- output_task = self.make_bedrock_api_request(
+ try:
+ output_content_bedrock = await self.make_bedrock_api_request(
source="OUTPUT",
response=response,
request_data=data,
logging_event_type=GuardrailEventHooks.post_call,
)
-
- # Execute both requests in parallel
- try:
- _, output_content_bedrock = await asyncio.gather(
- input_task, output_task
- )
- except GuardrailInterventionNormalStringError as e:
- output_content_bedrock = e.message
- else:
- # Only run OUTPUT validation (INPUT was already validated in pre_call or during_call)
- try:
- output_content_bedrock = await self.make_bedrock_api_request(
- source="OUTPUT",
- response=response,
- request_data=data,
- logging_event_type=GuardrailEventHooks.post_call,
- )
- except GuardrailInterventionNormalStringError as e:
- output_content_bedrock = e.message
+ except GuardrailInterventionNormalStringError as e:
+ output_content_bedrock = e.message
#########################################################
########## 2. Apply masking to response with output guardrail response ##########
@@ -1224,11 +1187,10 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):
"""
Process streaming response chunks.
- Collect content from the stream and make parallel bedrock api requests to get the guardrail responses.
+ Collect content from the stream and run the bedrock OUTPUT scan
+ (post_call only validates the response).
"""
# Import here to avoid circular imports
- import asyncio
-
from litellm.llms.base_llm.base_model_iterator import MockResponseIterator
from litellm.main import stream_chunk_builder
from litellm.types.utils import TextCompletionResponse
@@ -1245,61 +1207,24 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):
)
if isinstance(assembled_model_response, ModelResponse):
####################################################################
- ########## 1. Make Bedrock Apply Guardrail API requests ##########
-
- # Bedrock will raise an exception if this violates the guardrail policy
+ ########## 1. Make Bedrock Apply Guardrail API request ##########
+ #
+ # post_call only scans OUTPUT — input scanning belongs to
+ # pre_call / during_call. Bedrock will raise if the response
+ # violates the guardrail policy.
###################################################################
- # Determine if INPUT validation is needed in post_call
- # Skip INPUT validation if pre_call or during_call is already enabled
- # (to avoid redundant validation - those hooks would have already validated INPUT)
- should_validate_input = not (
- self._event_hook_is_event_type(GuardrailEventHooks.pre_call)
- or self._event_hook_is_event_type(GuardrailEventHooks.during_call)
- )
-
output_guardrail_response: Optional[
Union[BedrockGuardrailResponse, str]
] = None
-
- if should_validate_input:
- # Create tasks for parallel execution
- input_filter = self._prepare_guardrail_messages_for_role(
- messages=request_data.get("messages")
- )
- input_messages = input_filter.payload_messages or request_data.get(
- "messages"
- )
- input_task = self.make_bedrock_api_request(
- source="INPUT",
- messages=input_messages,
- request_data=request_data,
- logging_event_type=GuardrailEventHooks.post_call,
- ) # Only input messages
- output_task = self.make_bedrock_api_request(
+ try:
+ output_guardrail_response = await self.make_bedrock_api_request(
source="OUTPUT",
response=assembled_model_response,
request_data=request_data,
logging_event_type=GuardrailEventHooks.post_call,
- ) # Only response
-
- # Execute both requests in parallel
- try:
- _, output_guardrail_response = await asyncio.gather(
- input_task, output_task
- )
- except GuardrailInterventionNormalStringError as e:
- output_guardrail_response = e.message
- else:
- # Only run OUTPUT validation (INPUT was already validated in pre_call or during_call)
- try:
- output_guardrail_response = await self.make_bedrock_api_request(
- source="OUTPUT",
- response=assembled_model_response,
- request_data=request_data,
- logging_event_type=GuardrailEventHooks.post_call,
- )
- except GuardrailInterventionNormalStringError as e:
- output_guardrail_response = e.message
+ )
+ except GuardrailInterventionNormalStringError as e:
+ output_guardrail_response = e.message
#########################################################################
########## 2. Apply masking to response with output guardrail response ##########
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py
index fef984d7044..7dfdca118c6 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py
@@ -1810,14 +1810,19 @@ async def test_make_bedrock_api_request_logging_event_type_for_spend_logs():
"messages": [{"role": "user", "content": "hi"}],
}
- with patch.object(
- guardrail.async_handler, "post", new_callable=AsyncMock
- ) as mock_post, patch.object(
- guardrail, "_load_credentials", return_value=(mock_credentials, "us-east-1")
- ), patch.object(guardrail, "_prepare_request", return_value=MagicMock()), patch.object(
- guardrail,
- "add_standard_logging_guardrail_information_to_request_data",
- ) as mock_log:
+ with (
+ patch.object(
+ guardrail.async_handler, "post", new_callable=AsyncMock
+ ) as mock_post,
+ patch.object(
+ guardrail, "_load_credentials", return_value=(mock_credentials, "us-east-1")
+ ),
+ patch.object(guardrail, "_prepare_request", return_value=MagicMock()),
+ patch.object(
+ guardrail,
+ "add_standard_logging_guardrail_information_to_request_data",
+ ) as mock_log,
+ ):
mock_post.return_value = mock_bedrock_response
await guardrail.make_bedrock_api_request(
@@ -1826,7 +1831,9 @@ async def test_make_bedrock_api_request_logging_event_type_for_spend_logs():
request_data=request_data,
logging_event_type=GuardrailEventHooks.during_call,
)
- assert mock_log.call_args.kwargs["event_type"] == GuardrailEventHooks.during_call
+ assert (
+ mock_log.call_args.kwargs["event_type"] == GuardrailEventHooks.during_call
+ )
# Raw Bedrock JSON is forwarded; redaction runs once in
# CustomGuardrail.add_standard_logging_guardrail_information_to_request_data.
assert (
@@ -2035,11 +2042,13 @@ def test_get_http_exception_no_blocked_assessments_omits_field():
@pytest.mark.asyncio
-async def test_streaming_post_call_parallel_output_passes_request_data_to_make_bedrock():
+async def test_streaming_post_call_only_runs_output_scan():
"""
async_post_call_streaming_iterator_hook must pass request_data into OUTPUT
make_bedrock_api_request so spend/standard_logging attaches to the real request
(Greptile: previously OUTPUT used request_data=None / ephemeral {}).
+
+ post_call only validates the response — no INPUT scan should run here.
"""
request_data = {
"model": "gpt-4o-mini",
@@ -2111,8 +2120,7 @@ async def test_streaming_post_call_parallel_output_passes_request_data_to_make_b
input_calls = [
c for c in mock_make.call_args_list if c.kwargs.get("source") == "INPUT"
]
- assert len(input_calls) == 1
- assert input_calls[0].kwargs.get("request_data") is request_data
+ assert len(input_calls) == 0
@pytest.mark.asyncio
@@ -2164,3 +2172,60 @@ async def test_streaming_post_call_output_only_path_passes_request_data_to_make_
c = mock_make.call_args
assert c.kwargs.get("source") == "OUTPUT"
assert c.kwargs.get("request_data") is request_data
+
+
+# ---------------------------------------------------------------------------
+# Regression: post_call only validates OUTPUT.
+# Input scanning belongs to pre_call / during_call. Running an extra INPUT
+# scan here used to produce a duplicate "post-call" trace entry and made no
+# semantic sense for a "post-call" event.
+# ---------------------------------------------------------------------------
+
+
+async def test_post_call_success_hook_only_runs_output_scan():
+ """
+ With only `post_call` configured, async_post_call_success_hook must call
+ make_bedrock_api_request exactly once with source="OUTPUT". An INPUT call
+ here would produce a duplicate post-call log entry.
+ """
+ guardrail = BedrockGuardrail(
+ guardrail_name="bedrock-post-pii",
+ guardrailIdentifier="gid",
+ guardrailVersion="1",
+ event_hook=GuardrailEventHooks.post_call,
+ default_on=True,
+ )
+
+ request_data = {
+ "model": "gpt-4o-mini",
+ "messages": [{"role": "user", "content": "hi"}],
+ "metadata": {},
+ }
+ response = ModelResponse(
+ choices=[
+ litellm.Choices(
+ message=litellm.Message(role="assistant", content="hello"),
+ index=0,
+ finish_reason="stop",
+ )
+ ],
+ model="gpt-4o-mini",
+ )
+
+ minimal = {"action": "NONE", "assessments": [], "outputs": []}
+ with patch.object(
+ guardrail, "make_bedrock_api_request", AsyncMock(return_value=minimal)
+ ) as mock_make:
+ await guardrail.async_post_call_success_hook(
+ data=request_data,
+ user_api_key_dict=UserAPIKeyAuth(),
+ response=response,
+ )
+
+ sources = [c.kwargs.get("source") for c in mock_make.call_args_list]
+ assert sources == ["OUTPUT"]
+ assert (
+ mock_make.call_args.kwargs.get("logging_event_type")
+ == GuardrailEventHooks.post_call
+ )