Skip to content

Commit 2bbcf5a

Browse files
committed
Update bedrock_guardrails.py
1 parent a3f0a3c commit 2bbcf5a

File tree

1 file changed

+45
-4
lines changed

1 file changed

+45
-4
lines changed

litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -406,10 +406,38 @@ async def make_bedrock_api_request(
406406

407407
return bedrock_guardrail_response
408408

409-
def _check_bedrock_response_for_exception(self, response: httpx.Response) -> bool:
410-
return "Exception" in json.loads(response.content.decode("utf-8")).get(
411-
"Output", {}
412-
).get("__type", "")
409+
def _check_bedrock_response_for_exception(self, response) -> bool:
410+
"""
411+
Return True if the Bedrock ApplyGuardrail response indicates an exception.
412+
413+
Works with real httpx.Response objects and MagicMock responses used in tests.
414+
"""
415+
payload = None
416+
417+
try:
418+
json_method = getattr(response, "json", None)
419+
if callable(json_method):
420+
payload = json_method()
421+
except Exception:
422+
payload = None
423+
424+
if payload is None:
425+
try:
426+
raw = getattr(response, "content", None)
427+
if isinstance(raw, (bytes, bytearray)):
428+
payload = json.loads(raw.decode("utf-8"))
429+
else:
430+
text = getattr(response, "text", None)
431+
if isinstance(text, str):
432+
payload = json.loads(text)
433+
except Exception:
434+
# Can't parse -> assume no explicit Exception marker
435+
return False
436+
437+
if not isinstance(payload, dict):
438+
return False
439+
440+
return "Exception" in payload.get("Output", {}).get("__type", "")
413441

414442
def _get_bedrock_guardrail_response_status(
415443
self, response: httpx.Response
@@ -423,6 +451,19 @@ def _get_bedrock_guardrail_response_status(
423451
return "success"
424452
return "failure"
425453

454+
def _get_http_exception_for_failed_guardrail(
455+
self, response: httpx.Response
456+
) -> HTTPException:
457+
return HTTPException(
458+
status_code=400,
459+
detail={
460+
"error": "Guardrail application failed.",
461+
"bedrock_guardrail_response": json.loads(
462+
response.content.decode("utf-8")
463+
).get("Output", {}),
464+
},
465+
)
466+
426467
def _get_http_exception_for_blocked_guardrail(
427468
self, response: BedrockGuardrailResponse
428469
) -> HTTPException:

0 commit comments

Comments
 (0)