
    h                         d dl Z d dlmZmZmZ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 d dlmZmZ d dlmZmZ d dlmZ erd d	lmZ  G d
 de      Z G d de      Z G d de      Zy)    N)TYPE_CHECKINGAnyDictListLiteralOptionalTypeUnion)HTTPException)	DualCache)verbose_proxy_logger)CustomGuardraillog_guardrail_information)get_async_httpx_clienthttpxSpecialProvider)UserAPIKeyAuth)GuardrailConfigModelc                       e Zd Zy)LassoGuardrailMissingSecretsN)__name__
__module____qualname__     p/var/www/Befach/backend/env/lib/python3.12/site-packages/litellm/proxy/guardrails/guardrail_hooks/lasso/lasso.pyr   r      s    r   r   c                       e Zd ZdZy)LassoGuardrailAPIErrorz=Exception raised when there's an error calling the Lasso API.N)r   r   r   __doc__r   r   r   r   r   !   s    Gr   r   c                       e Zd Z	 	 	 	 	 ddee   dee   dee   dee   dee   f
 fdZeded	ed
e	de
d   deeee	df   f
d       Zed
e	dede
d   fd       Zd
e	fdZde	eef   fdZdeeeef      deeef   fdZdeeef   deeef   deeef   fdZdeeef   ddfdZdeeef   dee   fdZedeed      fd       Z xZS )LassoGuardrailNlasso_api_keyapi_keyapi_baseuser_idconversation_idc                    t        t        j                        | _        |xs# |xs t        j
                  j                  d      | _        |xs t        j
                  j                  d      | _        |xs t        j
                  j                  d      | _	        | j                  d}t        |      |xs t	        j                  d      xs d| _        t        | 8  di | y )	N)llm_providerLASSO_API_KEYLASSO_USER_IDLASSO_CONVERSATION_IDCouldn't get Lasso api key, either set the `LASSO_API_KEY` in the environment or pass it as a parameter to the guardrail in the config fileLASSO_API_BASEzhttps://server.lasso.securityr   )r   r   GuardrailCallbackasync_handlerosenvirongetr!   r$   r%   r   getenvr#   super__init__)	selfr!   r"   r#   r$   r%   kwargsmsg	__class__s	           r   r4   zLassoGuardrail.__init__(   s     4-??
 +XgX9XA"**.."A.  
"**..#3
 %M  /s33 V		"23V7V 	 	"6"r   user_api_key_dictcachedata	call_type)
completiontext_completion
embeddingsimage_generation
moderationaudio_transcriptionpass_through_endpointrerankreturnc                 j   K   t        j                  d       | j                  |       d {   S 7 w)NzInside Lasso Pre-Call Hookr   debugrun_lasso_guardrail)r5   r9   r:   r;   r<   s        r   async_pre_call_hookz"LassoGuardrail.async_pre_call_hookF   s.     " 	""#?@--d3333   *313)r=   r?   r@   rA   rB   	responsesc                 j   K   t        j                  d       | j                  |       d{   S 7 w)z9
        This is used for during_call moderation
        zInside Lasso Moderation HookNrG   )r5   r;   r9   r<   s       r   async_moderation_hookz$LassoGuardrail.async_moderation_hookZ   s.     " 	""#AB--d3333rK   c                   K   |j                  dg       }|s|S 	 | j                         }| j                  |      }| j                  ||       d{   }| j	                  |       |S 7 # t
        $ rO}t        |t              r|t        j                  dt        |              t        dt        |             d}~ww xY ww)zz
        Run the Lasso guardrail

        Raises:
            LassoGuardrailAPIError: If the Lasso API call fails
        messages)headerspayloadNzError calling Lasso API: z0Failed to verify request safety with Lasso API: )r1   _prepare_headers_prepare_payload_call_lasso_api_process_lasso_response	Exception
isinstancer   r   errorstrr   )r5   r;   rP   rQ   rR   responsees          r   rI   z"LassoGuardrail.run_lasso_guardrailn   s      *.*b)AK	++-G++H5G!11 2  H ((2K  	!]+ &&)B3q6('KL(B3q6(K 	s;   C7A+ A)A+ (C)A+ +	C4A
B>>CCc                     | j                   sd}t        |      | j                   dd}| j                  r| j                  |d<   | j                  r| j                  |d<   |S )z*Prepare headers for the Lasso API request.r+   zapplication/json)zlasso-api-keyzContent-Typezlasso-user-idzlasso-conversation-id)r!   r   r$   r%   )r5   r7   rQ   s      r   rS   zLassoGuardrail._prepare_headers   sn    !!M  /s33 "//.#
 <<'+||GO$/3/C/CG+,r   rP   c                 
    d|iS )z.Prepare the payload for the Lasso API request.rP   r   )r5   rP   s     r   rT   zLassoGuardrail._prepare_payload   s    H%%r   rQ   rR   c                   K   t        j                  d|        | j                  j                  | j                   d||d       d{   }|j                          |j                         }t        j                  d|        |S 7 >w)z+Call the Lasso API and return the response.zSending request to Lasso API: z/gateway/v2/classifyg      $@)urlrQ   jsontimeoutNzLasso API response: )r   rH   r.   postr#   raise_for_statusra   )r5   rQ   rR   r[   ress        r   rU   zLassoGuardrail._call_lasso_api   s      	""%CG9#MN++00==/!56	 1 
 
 	!!#mmo""%9##?@

s   AB
B	?Br[   c                     |r`|j                  d      du rL| j                  |      }t        j                  d|        t	        ddddj                  |       |d	      y
y
)zOProcess the Lasso API response and raise exceptions if violations are detected.violations_detectedTz%Lasso guardrail detected violations: i  zViolated Lasso guardrail policyzGuardrail violations detected: z, )rY   detection_messagelasso_response)status_codedetailN)r1   _parse_violated_deputiesr   warningr   join)r5   r[   violated_deputiess      r   rV   z&LassoGuardrail._process_lasso_response   s{    %:;tC $ = =h G ((78I7JK  >+J499UfKgJh)i&.  D8r   c                 p    g }d|v r/|d   j                         D ]  \  }}|s	|j                  |        |S )z0Parse the response to extract violated deputies.deputies)itemsappend)r5   r[   ro   deputyis_violateds        r   rl   z'LassoGuardrail._parse_violated_deputies   sG    !'/
';'A'A'C#%,,V4 (D ! r   r   c                      ddl m}  | S )Nr   LassoGuardrailConfigModel)4litellm.types.proxy.guardrails.guardrail_hooks.lassorx   rw   s    r   get_config_modelzLassoGuardrail.get_config_model   s    	
 )(r   )NNNNN)r   r   r   r   rZ   r4   r   r   r   dictr   r
   rW   rJ   rN   rI   rS   r   r   r   rT   rU   rV   rl   staticmethodr	   rz   __classcell__)r8   s   @r   r    r    '   s    (,!%"&!%)-#}# ## 3-	#
 ## "##< 4)4 4 	4
 	
4 
y#tT)	*4 4& 44 *4 
	4 4&!!F$sCx. .&d38n)= &$sCx. &CH~04S#X	c3h S#X 4  !c3h !DI ! )ht,B'CD ) )r   r    )r/   typingr   r   r   r   r   r   r	   r
   fastapir   litellmr   litellm._loggingr   %litellm.integrations.custom_guardrailr   r   &litellm.llms.custom_httpx.http_handlerr   r   litellm.proxy._typesr   3litellm.types.proxy.guardrails.guardrail_hooks.baser   rW   r   r   r    r   r   r   <module>r      sW    
 Q Q Q !  1 0X	9 		Y 	t)_ t)r   