
    g%                      p    d dl mZmZmZmZmZ d dlmZ d dlm	Z	 d dl
mZmZ d dlmZ  G d de	      Zd Zy	)
    )DictListLiteralOptionalUnion)verbose_logger)CustomLogger)DynamicGuardrailParamsGuardrailEventHooks)#StandardLoggingGuardrailInformationc            	           e Zd Z	 	 	 ddee   deee      dee   f fdZdede	ee   ee
eef      f   fdZd	e	ee   ee
eef      f   defd
ZdedefdZdedefdZdefdZde	eeef   deded   ddfdZ xZS )CustomGuardrailNguardrail_namesupported_event_hooks
event_hookc                     || _         || _        || _        |r|r||vrt        d| d|       t	        |   di | y )NzEvent hook z% is not in the supported event hooks  )r   r   r   
ValueErrorsuper__init__)selfr   r   r   kwargs	__class__s        Z/var/www/openai/venv/lib/python3.12/site-packages/litellm/integrations/custom_guardrail.pyr   zCustomGuardrail.__init__   s\     -%:"9C j0EE !*-RShRij  	"6"    datareturnc                 Z    |j                  d      xs i }|j                  d      xs g }|S )zF
        Returns the guardrail(s) to be run from the metadata
        metadata
guardrails)get)r   r   r   requested_guardrailss       r   get_guardrail_from_metadataz+CustomGuardrail.get_guardrail_from_metadata   s1     88J'-2'||L9?R##r   r"   c                     |D ]E  }t        |t              r| j                  |v s" yt        |t              s5| j                  |k(  sE y y)NTF)
isinstancedictr   str)r   r"   
_guardrails      r   %_guardrail_is_in_requested_guardrailsz5CustomGuardrail._guardrail_is_in_requested_guardrails(   sI     /J*d+&&*4J,&&*4 / r   
event_typec                 &   | j                  |      }t        j                  d| j                  || j                  |       | j                  r!| j                  |      s|j                  dk7  ry| j                  r| j                  |j                  k7  ryy)Nzxinside should_run_guardrail for guardrail=%s event_type= %s guardrail_supported_event_hooks= %s requested_guardrails= %slogging_onlyFT)r#   r   debugr   r   r)   value)r   r   r*   r"   s       r   should_run_guardrailz$CustomGuardrail.should_run_guardrail5   s    #??E GOO 	
 OO>>?ST  N2??t*2B2BBr   request_datac                     | j                  |      }|D ]c  }t        |t              s| j                  |v s#t	        di || j                     }| j                         duri c S |j                  di       c S  i S )a  
        Returns `extra_body` to be added to the request body for the Guardrail API call

        Use this to pass dynamic params to the guardrail API call - eg. success_threshold, failure_threshold, etc.

        ```
        [{"lakera_guard": {"extra_body": {"foo": "bar"}}}]
        ```

        Will return: for guardrail=`lakera-guard`:
        {
            "foo": "bar"
        }

        Args:
            request_data: The original `request_data` passed to LiteLLM Proxy
        T
extra_bodyr   )r#   r%   r&   r   r
   _validate_premium_userr!   )r   r0   r"   	guardrailguardrail_configs        r   )get_guardrail_dynamic_request_body_paramsz9CustomGuardrail.get_guardrail_dynamic_request_body_paramsL   s    $  $??M .I)T*t/B/Bi/O;Q < 3 34<  ..0<I (++L"== . 	r   c                 v    ddl m}m} |dur-t        j                  d|j
                  j                          yy)z<
        Returns True if the user is a premium user
        r   )CommonProxyErrorspremium_userTz5Trying to use premium guardrail without premium user F)litellm.proxy.proxy_serverr8   r9   r   warningnot_premium_userr.   )r   r8   r9   s      r   r3   z&CustomGuardrail._validate_premium_usero   s>     	Ot#""GHYHjHjHpHpGqr r   guardrail_json_responseguardrail_status)successfailurec                 R   ddl m} |dur0t        j                  d| j                   d| j
                          yt        |t              rt        |      }t        | j                  | j
                  ||      }d|v r	||d   d	<   yd
|v r	||d
   d	<   yt        j                  d       y)z
        Builds `StandardLoggingGuardrailInformation` and adds it to the request metadata so it can be used for logging to DataDog, Langfuse, etc.
        r   )r9   Tz`Guardrail Tracing is only available for premium users. Skipping guardrail logging for guardrail=z event_hook=N)r   guardrail_modeguardrail_responser>   r   &standard_logging_guardrail_informationlitellm_metadatazFunable to log guardrail information. No metadata found in request_data)
r:   r9   r   r;   r   r   r%   	Exceptionr'   r   )r   r=   r0   r>   r9   slgs         r   :add_standard_logging_guardrail_information_to_request_datazJCustomGuardrail.add_standard_logging_guardrail_information_to_request_data|   s     	<t#""rsw  tG  tG  sH  HT  UY  Ud  Ud  Te  f -y9&)*A&B#1..??6-	
 %QTL$%MN</  +,8 ""Xr   )NNN)__name__
__module____qualname__r   r'   r   r   r   r&   r   r   r
   r#   boolr)   r/   r6   r3   rF   r   rH   __classcell__)r   s   @r   r   r   	   s    )-EI48	# #  (-@(AB# 01	#&$$	tCy$tC)?$?@AA	B$#DItD>T9T4U/V$VW 
5H T .!d !t !F !!&y#t';!<! ! ""67	!
 
!r   r   c                      ddl ddl}d d |j                          fd       |j                          fd       |j                          fd       }|S )ad  
    Decorator to add standard logging guardrail information to any function

    Add this decorator to ensure your guardrail response is logged to DataDog, OTEL, s3, GCS etc.

    Logs for:
        - pre_call
        - during_call
        - TODO: log post_call. This is more involved since the logs are sent to DD, s3 before the guardrail is even run
    r   Nc                 .    | j                  ||d       |S )Nr?   r=   r0   r>   rH   )r   responser0   s      r   process_responsez3log_guardrail_information.<locals>.process_response   s&    GG$,%& 	H 	

 r   c                 .    | j                  ||d       |)Nr@   rP   rQ   )r   er0   s      r   process_errorz0log_guardrail_information.<locals>.process_error   s&    GG$%%& 	H 	

 r   c                     K   | d   }|j                  d      xs |j                  d      xs i }	  | i | d {   } |||      S 7 # t        $ r} |||      cY d }~S d }~ww xY wwNr   r   r0   r!   rF   	argsr   r   r0   rR   rU   funcrV   rS   s	         r   async_wrapperz0log_guardrail_information.<locals>.async_wrapper   s}      $QJJvB&**^"<B 		8!42622H#D(LAA 3 	8 q,77	8sD   .A.A AA A.A 	A+	A& A+!A.&A++A.c                      | d   }|j                  d      xs |j                  d      xs i }	  | i |} |||      S # t        $ r} |||      cY d }~S d }~ww xY wrX   rY   rZ   s	         r   sync_wrapperz/log_guardrail_information.<locals>.sync_wrapper   sr     $QJJvB&**^"<B 		8T,V,H#D(LAA 	8 q,77	8s   A 	A	AAAc                  F    j                        r | i |S  | i |S )N)iscoroutinefunction)r[   r   r]   asyncior\   r_   s     r   wrapperz*log_guardrail_information.<locals>.wrapper   s1    &&t, $1&11T,V,,r   )rb   	functoolswraps)r\   rd   rc   r]   rb   rV   rS   r_   s   `  @@@@@r   log_guardrail_informationrf      ss      __T	8 	8 __T	8 	8 __T- -
 Nr   N)typingr   r   r   r   r   litellm._loggingr   "litellm.integrations.custom_loggerr	   litellm.types.guardrailsr
   r   litellm.types.utilsr   r   rf   r   r   r   <module>rl      s+    7 7 + ; P CTl Tn<r   