
    hnO              
       b   U d dl Z d dlZd dlZd dlmZmZ d dlmZmZmZm	Z	m
Z
 d dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZmZmZmZmZ d
dlmZmZmZm Z m!Z! ejD                  jF                  eejH                  jF                  eejJ                  jF                  e ejL                  jF                  e!ejN                  jF                  eiZ(i Z)ee*e	e   f   e+d<   d Z,d Z-e)j]                   e-               e,       Z/e(j]                  e/        G d d      Z0 G d d      Z1 e1       Z2y)    N)datetimetimezone)DictListOptionalTypecast)verbose_proxy_logger)CustomGuardrail)
safe_dumps)PrismaClient)
get_secret)	GuardrailGuardrailEventHooksLakeraCategoryThresholdsLitellmParamsSupportedGuardrailIntegrations   )initialize_bedrockinitialize_hide_secretsinitialize_lakerainitialize_lakera_v2initialize_presidioguardrail_class_registryc            
         i } 	 t         j                  j                  t              }t         j                  j	                  |d      }t         j                  j                  |      st        j                  d       | S t        j                  |      D ]h  }t         j                  j	                  ||      }t         j                  j                  |      r|j                  d      rUt         j                  j	                  |d      }t         j                  j                  |      sd| }	 t        j                  d|        t        j                  |      }t        |d      r`t        |d      }t        |t               ry| j#                  |       t        j                  d| d	t%        |j'                                       n5t        |d
      r)t        |d
      }	|	| |<   t        j                  d|        k t        j                  dt/        |        dt%        | j'                                       | S # t(        $ r&}
t        j*                  d| d	|
        Y d}
~
d}
~
wt,        $ r&}
t        j*                  d| d	|
        Y d}
~
 d}
~
ww xY w# t,        $ r#}
t        j*                  d|
        Y d}
~
| S d}
~
ww xY w)a  
    Get guardrail initializers by discovering them from the guardrail_hooks directory structure.

    Scans the guardrail_hooks directory for subdirectories containing __init__.py files
    with either guardrail_initializer_registry or initialize_guardrail functions.

    Returns:
        Dict[str, Callable]: A dictionary mapping guardrail types to their initializer functions
    guardrail_hooks#guardrail_hooks directory not found____init__.py)litellm.proxy.guardrails.guardrail_hooks.Discovering guardrails in: guardrail_initializer_registryz(Found guardrail_initializer_registry in : initialize_guardrailz'Found initialize_guardrail function in Could not import NError processing zDiscovered z guardrail initializers: *Error discovering guardrail initializers: )ospathdirname__file__joinexistsr
   debuglistdirisdir
startswith	importlibimport_modulehasattrgetattr
isinstancedictupdatelistkeysImportErrorerror	Exceptionlen)discovered_initializerscurrent_dir	hooks_diritem	item_path	init_filemodule_pathmoduleregistryinitialize_fnes              g/var/www/Befach/backend/env/lib/python3.12/site-packages/litellm/proxy/guardrails/guardrail_registry.py$get_guardrail_initializer_from_hooksrK   *   st    !;Uggooh/GGLL.?@	ww~~i( &&'LM** JJy)DY5I 77==+tt/D Y>I77>>),EdVLK$**-H+VW"00= 6#CD&v/OPH!(D1/66x@,22F{mSUVZ[c[h[h[jVkUlm
 V%;<$+F4J$KM4A+D1(..A+OC *X 	""#5677PQUVmVrVrVtQuPvw	
 #"  $**->{m2aS+QR $**->{m2aS+QR  U""%OPQs#STT""Us\   A8J =B/J -CH;;>J ;	JI%J %J1JJ JJ 	K#KKc                  P   	 i } 	 t         j                  j                  t              }t         j                  j	                  |d      }t         j                  j                  |      st        j                  d       | S t        j                  |      D ]   }t         j                  j	                  ||      }t         j                  j                  |      r|j                  d      rUt         j                  j	                  |d      }t         j                  j                  |      sd| }	 t        j                  d|        t        j                  |      }t        |d      r-t        |d      }t        |t               r| j#                  |        	 | S # t$        $ r&}	t        j                  d| d	|	        Y d
}	~	1d
}	~	wt&        $ r&}	t        j(                  d| d	|	        Y d
}	~	^d
}	~	ww xY w# t&        $ r#}	t        j*                  d|	        Y d
}	~	| S d
}	~	ww xY w)za
    Get guardrail classes by discovering them from the guardrail_hooks directory structure.
    r   r   r   r   r    r!   r   r%   r#   Nr&   r'   )r(   r)   r*   r+   r,   r-   r
   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r;   r=   	exceptionr<   )
discovered_classesr@   rA   rB   rC   rD   rE   rF   rG   rI   s
             rJ   get_guardrail_class_from_hooksrO   v   s    -Uggooh/GGLL.?@	ww~~i( &&'LM%% JJy)DY5I 77==+tt/D Y>I77>>),EdVLK$**-H+VW"00= 6#=>&v/IJH!(D1*11(;3 *J   $**->{m2aS+QR $..1B;-rRSQT/UV  U""%OPQs#STTUs\   A8G9 >B/G9 .A&FG9 	G6#G>G9 G6G1+G9 1G66G9 9	H%H  H%c                       e Zd ZdZd Zdedee   fdZde	de
fdZd	ede
fd
Zd	ede	de
fdZede
dee	   fd       Zd	ede
dee	   fdZdede
dee	   fdZy)GuardrailRegistryzi
    Registry for guardrails

    Handles adding, removing, and getting guardrails in DB + in memory
    c                      y N selfs    rJ   __init__zGuardrailRegistry.__init__   s        guardrail_namereturnc                     t         j                  j                  t              }|D ]&  }t	        |t              s|j
                  |k(  s$|c S  y)zW
        Returns the initialized guardrail callback for a given guardrail name
        )callback_typeN)litellmlogging_callback_managerget_custom_loggers_for_typer   r6   rY   )rV   rY   active_guardrailsactive_guardrails       rJ   "get_initialized_guardrail_callbackz4GuardrailRegistry.get_initialized_guardrail_callback   sW     ,,HH- I  	
 !2*O<#22nD++ !2 rX   	guardrailprisma_clientc           	      $  K   	 |j                  d      }t        t        |j                  di                   }t        |j                  di             }|j                  j                  j                  |||t        j                  t        j                        t        j                  t        j                        d       d{   }t        |      }|j                  |d<   |S 7  # t        $ r}t        dt        |             d}~ww xY ww)	z1
        Add a guardrail to the database
        rY   litellm_paramsguardrail_info)rY   rf   rg   
created_at
updated_at)dataNguardrail_idzError adding guardrail to DB: )getr   r7   dblitellm_guardrailstablecreater   nowr   utcrk   r=   str)	rV   rc   rd   rY   rf   rg   created_guardrailguardrail_dictrI   s	            rJ   add_guardrail_to_dbz%GuardrailRegistry.add_guardrail_to_db   s     	G&]]+;<N",T)--@PRT2U-V"WN",Y]];KR-P"QN '4&6&6&N&N&U&U&4&4&4"*,,x||"<"*,,x||"< 'V ' ! ")_N->-K-KN>*!!!  	G<SVHEFF	Gs;   DCC( C&C( %D&C( (	D1DDDrk   c                    K   	 |j                   j                  j                  d|i       d{    dd| diS 7 # t        $ r}t        dt	        |             d}~ww xY ww)z6
        Delete a guardrail from the database
        rk   whereNmessagez
Guardrail z deleted successfullyz"Error deleting guardrail from DB: )rm   rn   deleter=   rr   )rV   rk   rd   rI   s       rJ   delete_guardrail_from_dbz*GuardrailRegistry.delete_guardrail_from_db   s     	K""::AA%|4 B    L>9NOPP	
  	K@QIJJ	Ks1   A&+> <> A&> 	A#AA##A&c           	        K   	 |j                  d      }t        t        |j                  di                   }t        |j                  di             }|j                  j                  j                  d|i|||t        j                  t        j                        d       d{   }t        |      S 7 # t        $ r}t        dt        |             d}~ww xY ww)	z4
        Update a guardrail in the database
        rY   rf   rg   rk   )rY   rf   rg   ri   )rx   rj   Nz Error updating guardrail in DB: )rl   r   r7   rm   rn   r8   r   rp   r   rq   r=   rr   )	rV   rk   rc   rd   rY   rf   rg   updated_guardrailrI   s	            rJ   update_guardrail_in_dbz(GuardrailRegistry.update_guardrail_in_db  s     	I&]]+;<N",T)--@PRT2U-V"WN",Y]];KR-P"QN '4&6&6&N&N&U&U%|4&4&4&4"*,,x||"<	 'V ' ! )**!  	I>s1vhGHH	Is;   C B"B8 &B6'B8 5C 6B8 8	CCCC c           
        K   	 | j                   j                  j                  ddi       d{   }g }|D ]%  }|j                  t	        di t        |             ' |S 7 2# t        $ r}t        dt        |             d}~ww xY ww)z6
        Get all guardrails from the database
        rh   desc)orderNz"Error getting guardrails from DB: rT   )rm   rn   	find_manyappendr   r7   r=   rr   )rd   guardrails_from_db
guardrailsrc   rI   s        rJ   get_all_guardrails_from_dbz,GuardrailRegistry.get_all_guardrails_from_db*  s     	K#&&>>HH'0 I    +-J/	!!)"@tI"@A 0   	K@QIJJ	Ks8   B+A$ A"1A$ !B"A$ $	B	-BB		Bc                    K   	 |j                   j                  j                  d|i       d{   }|syt        di t	        |      S 7 # t
        $ r}t        dt        |             d}~ww xY ww)z=
        Get a guardrail by its ID from the database
        rk   rw   N!Error getting guardrail from DB: rT   rm   rn   find_uniquer   r7   r=   rr   )rV   rk   rd   rc   rI   s        rJ   get_guardrail_by_id_from_dbz-GuardrailRegistry.get_guardrail_by_id_from_db@  s     
	J+..FFRR%|4 S  I 1Y11  	J?AxHII	JB   A5+A AA A5A 
A5A 	A2A--A22A5c                    K   	 |j                   j                  j                  d|i       d{   }|syt        di t	        |      S 7 # t
        $ r}t        dt        |             d}~ww xY ww)z?
        Get a guardrail by its name from the database
        rY   rw   Nr   rT   r   )rV   rY   rd   rc   rI   s        rJ   get_guardrail_by_name_from_dbz/GuardrailRegistry.get_guardrail_by_name_from_dbR  s     
	J+..FFRR'8 S  I 1Y11  	J?AxHII	Jr   N)__name__
__module____qualname____doc__rW   rr   r   r   rb   r   r   ru   r{   r~   staticmethodr   r   r   r   rT   rX   rJ   rQ   rQ      s    !	/	"(G"G3?G<KK0<K II,5IFRI6 K#K	iK K*JJ0<J	)	J$J!J2>J	)	JrX   rQ   c                       e Zd ZdZd Z	 ddedee   dee   fdZ	 dde	ded	e
dee   dee   f
d
ZdededdfdZdeddfdZdee   fdZdedee   fdZy)InMemoryGuardrailHandlerz[
    Class that handles initializing guardrails and adding them to the CallbackManager
    c                 "    i | _         	 i | _        y rS   )IN_MEMORY_GUARDRAILS guardrail_id_to_custom_guardrailrU   s    rJ   rW   z!InMemoryGuardrailHandler.__init__j  s     :<!	 WY-	rX   Nrc   config_file_pathrZ   c                 *   |j                  d      xs t        t        j                               }||d<   || j                  v r$t        j                  d       | j                  |   S d}|d   }t        j                  d|       t        |t              rt        di |}n|}d|v r|d   rt        di |d   }||_        |j                  r>|j                  j                  d      r#t        t        |j                              |_        |j                  r>|j                  j                  d      r#t        t        |j                              |_        |j                   }|t#        d      t$        j                  |      }	|	r
 |	||      }nFt        |t              r(d	|v r$| j'                  t)        t        |      |||
      }nt#        d|       t+        |j                  d      |d   |      }
|
| j                  |<   || j,                  |<   |
S )z
        Initialize a guardrail from a dictionary and add it to the litellm callback manager

        Returns a Guardrail object if the guardrail is initialized successfully
        rk   z3guardrail_id already exists in IN_MEMORY_GUARDRAILSNrf   zlitellm_params= %scategory_thresholdszos.environ/zguardrail_type is required.)rc   guardrail_typerf   r   zUnsupported guardrail: rY   )rk   rY   rf   rT   )rl   rr   uuiduuid4r   r
   r.   r6   r7   r   r   r   api_keyr1   r   api_baserc   
ValueErrorr"   initialize_custom_guardrailr	   r   r   )rV   rc   r   rk   custom_guardrail_callbacklitellm_params_datarf   lakera_category_thresholdsr   initializerparsed_guardrails              rJ   r$   z-InMemoryGuardrailHandler.initialize_guardrailu  s    !}}^4IDJJL8I$0	.!4444 &&E ,,\::?C!'(89""#79LM)40*A-@AN0N "%88#$9:)A *%&;<*& 2LN.!!n&<&<&G&G&V%(N4J4J)K%LN"""~'>'>'I'I(
 '**^5L5L*M&NN#'11!9::488H(3NI(N%,1F(,(H(HtY/--!1	 )I )% 6~6FGHH$"~6$%56)
 3C!!,/>W--l;rX   r   rf   c                    |st        d      |j                  d      \  }}t        j                  d|||       t        j
                  j                  |      }t        j
                  j                  ||      dz   }t        j                  j                  ||      }	|	st        d|       t        j                  j                  |	      }
|	j                  j                  |
       t        |
|      }|j                   }|$t#        d| ddj                  t$                     |j&                  } ||d	   ||
      }t(        j*                  j-                  |       |S )z
        Initialize a Custom Guardrail from a python file

        This initializes it by adding it to the litellm callback manager
        zTGuardrailsAIException - Please pass the config_file_path to initialize_guardrails_v2r   z@Initializing custom guardrail: %s, file_name: %s, class_name: %sz.pyz*Could not find a module specification for zmode is required for guardrail z* please set mode to one of the following: z, rY   )rY   
event_hook
default_on)r=   splitr
   r.   r(   r)   r*   r,   r2   utilspec_from_file_locationr;   module_from_specloaderexec_moduler5   moder   r   r   r]   r^   add_litellm_callback)rV   rc   r   rf   r   
_file_name_class_name	directorymodule_file_pathspecrF   _guardrail_classr   r   _guardrail_callbacks                  rJ   r   z4InMemoryGuardrailHandler.initialize_custom_guardrail  so     f  #1"6"6s";
K""N		
 GGOO$45	77<<	:>F~~55kCST<=M<NO  006'"6;7""<1.1AAklplulu  wJ  mK  lL  M  $..
.$%56!

 	((==>QR""rX   rk   c                     || j                   |<   | j                  j                  |      }|r3t        t        |j                  di             }|j                  |       yy)z
        Update a guardrail in memory

        - updates the guardrail in memory
        - updates the guardrail params in litellm.callback_manager
        rf   )rf   N)r   r   rl   r	   r   update_in_memory_litellm_params)rV   rk   rc   r   updated_litellm_paramss        rJ   update_in_memory_guardrailz3InMemoryGuardrailHandler.update_in_memory_guardrail  sm     3<!!,/$($I$I$M$M%
! %%)y}}-=rB&" &EE5 F 	 %rX   c                 <    | j                   j                  |d       y)z.
        Delete a guardrail in memory
        N)r   poprV   rk   s     rJ   delete_in_memory_guardrailz3InMemoryGuardrailHandler.delete_in_memory_guardrail  s     	!!%%lD9rX   c                 H    t        | j                  j                               S )z/
        List all guardrails in memory
        )r9   r   valuesrU   s    rJ   list_in_memory_guardrailsz2InMemoryGuardrailHandler.list_in_memory_guardrails  s     D--44677rX   c                 8    | j                   j                  |      S )z7
        Get a guardrail by its ID from memory
        )r   rl   r   s     rJ   get_guardrail_by_idz,InMemoryGuardrailHandler.get_guardrail_by_id  s     ((,,\::rX   rS   )r   r   r   r   rW   r   r   rr   r$   r   r   r   r   r   r   r   r   r   rT   rX   rJ   r   r   e  s    	 +/H H  #3-H  
)		H ^ +/4#4# 4# &	4#
 #3-4# 
/	"4#l,5	,:s :t :84	? 8; ;8K ;rX   r   )3r2   r(   r   r   r   typingr   r   r   r   r	   r]   litellm._loggingr
   %litellm.integrations.custom_guardrailr   *litellm.litellm_core_utils.safe_json_dumpsr   litellm.proxy.utilsr   litellm.secret_managers.mainr   litellm.types.guardrailsr   r   r   r   r   guardrail_initializersr   r   r   r   r   BEDROCKvalueLAKERA	LAKERA_V2PRESIDIOHIDE_SECRETSr"   r   rr   __annotations__rK   rO   r8   _discovered_initializersrQ   r   IN_MEMORY_GUARDRAIL_HANDLERrT   rX   rJ   <module>r      s#    	  ' 3 3  1 A A , 3   #**002D"))//1B",,224H"++113F"//557N"  >@ $sD$99: ?I#X>B    > @ A @A   % %&> ?bJ bJJv; v;x 78 rX   