@@ -406,10 +406,38 @@ async def make_bedrock_api_request(
406
406
407
407
return bedrock_guardrail_response
408
408
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" , "" )
413
441
414
442
def _get_bedrock_guardrail_response_status (
415
443
self , response : httpx .Response
@@ -423,6 +451,19 @@ def _get_bedrock_guardrail_response_status(
423
451
return "success"
424
452
return "failure"
425
453
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
+
426
467
def _get_http_exception_for_blocked_guardrail (
427
468
self , response : BedrockGuardrailResponse
428
469
) -> HTTPException :
0 commit comments